Use node. js to write a background server---Express frame construction and use

Source: Internet
Author: User

First, node.js+express framework of Service project construction

Step1: Create a project directory: MYAPP

Step2: The command line enters the directory and executes:

NPM Init

During the execution of the command, you will be asked to set a project's entry file (entry point), which you can optionally set for example: Index.js.

Once executed, a Package.json file is created in the project, which is used to manage some of the modules or dependencies that will be installed in the project in the future.

Step3: Install Express plugin:

NPM Install Express--save

Step4:express Core Service Code:

var express = require (' Express '); var app = Express (); App.get (function  (req, res) {  res.send (' Hello world! ') );}); var function () {  var host = server.address (). Address;   var port = server.address (). Port;  Console.log (' Example app listening at http://%s:%s ', host, Port);});

Copy this code into index.js.

STEP5: Start Service:

Node Index.js

To try to access localhost:3000, the browser appears as follows:

Such a super-simple express-based server is built.

Second, the above code simple explanation:

 //After installing Express, import the Express framework into
varExpress = require (' Express ');
initialization of the//express varApp =Express ();
//Here is a route, when get access to the root directory, it will execute app.get (‘/‘,function(req, res) {Res.send (' Hello world! ');});
//Monitor native 3000 port number varServer = App.listen (3000,function () { varHost =server.address (). Address; varPort =server.address (). Port; Console.log (' Example app listening at http://%s:%s ', host, Port);});

Third, how to deal with too many routes?

Q: What is routing in a brief introduction?

A: The popular route is the access path, different access paths execute different processing logic.

Routing (Routing) consists of a URI (or path) and a specific HTTP method (GET, POST, etc.) that relate to how the application responds to client access to a site node.

Each route can have one or more processor functions, which are executed when the route is matched.

So now the problem is, a daemon will have to provide a lot of data interface, that is to configure a lot of different routes, consider the following situation:

Now there is a add and remove the function interface needs us to complete, if we put it all under the Index.js file, it will make the program bloated and very difficult to maintain,

So how to manage routing is especially important!

Naturally we think of the sub-module to manage (Insert.js, Delete.js, Query.js), temporarily only consider the red box up part.

Step1: Create a router.js in your project (this file is used to manage different routing modules)

1Module.exports =functionRoute (APP) {2     //used to process queries3     varquery = require ('./api/query '));4App.use ('/query ', query);5 6 7     //used to handle insertions8     varInsert = require ('./api/insert '));9App.use ('/insert ', insert);Ten  One     //used to handle deletes A     vardel = require ('./api/delete ')); -App.use ('/delete ', Del); -}

Step2: Create Insert.js, Delete.js, query.js according to the file structure above

For example Delete.js:

1 /**2 * Administrator Module Delete.js3 * @authors Lewis4 * @date May 23, 2018 10:13:295 * @description used to delete resource data from the database6  */7 8  9 var express = require (' Express '); ten var router = Express. Router ();  One   router.get ('/', function(req, res) { res.send ({  ' success ': ' Delete success! ' (  ) ) ;  -   module.exports = router;

This is one of the simplest delete.js files inside the content, when accessing localhost:3000/delete, will enter the above method to execute the logic.

Of course, in this case, you can expand some of the methods of deletion, for example:

1  function (req, res) {2    res.send ({3          ' success ': ' Delete all data success! ') 4      })5  });

When accessing Localhost:3000/delete/all, the corresponding method is executed. The rest of the modules are similar, not more.

Step3: Associate Router.js with Express app:

Add the following code to the Index.js:

This allows us to modularize the routing and make it easier to manage.

  

Use node. js to write a background server---Express frame construction and use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.