preface

I have written simple Node server code before, but it is not a project. This time I wrote this back-end template because I also need it.

Some node templates found on Git can be implemented, but it is a little difficult to understand the workflow. Maybe because of my limited level, I collected a lot of source code and wrote this template according to my own understanding. Basic channels have been opened, there is no front-end page, only an input box and a button to request back-end data, print display in the console. Pure back-end development code.

Source code on gitee above, the need for partners can be downloaded. Each line of code has a detailed comment, here is mainly to explain the code workflow and the distribution of the main modules.

Download operation

To download the source code locally from Gitee, first make sure the Node environment is installed locally. The test method is to enter node -v on the command line. If the version number is displayed, it indicates that the Node environment is installed.

Open the CMD command line in the current directory and type NPM install to install the dependencies required by the project. After the installation is complete, you can find an additional node_modules folder in the project.

Above and the deployment of the project is completed, the next is to run, or in the current directory NPM start run the following command line, in the lead the code is run successfully, then you don’t have to close the command line, let him run, is the equivalent of a server has been running locally, we can begin the request data later.

> basestationserver@0.0. 0 start D:\.project\myself\BaseStationServer
> node ./bin/www
Copy the code

New project

If you don’t want to use my code, you can also create a New Node project, still need your environment, under the specified folder directory open CMD command window.

NPM install -g Express. After installing the express framework, the project cannot be generated. You need to install an Express-Generator. Run the command NPM install -g express-generator. This step is also a global installation, after which there is no need to install these two things again.

Then we run express projectName on the command line of the currently specified directory. ProjectName is the projectName you want to create yourself. When you’re done, you’ll see a project generated and go to the newly created project directory. Open a CMD window command line and type NPM install to install dependencies. At this point, the project and creation are complete.

To access the Node server, type localhost:3000 into your browser.

And you’re done! But did you think it was over? No, the point is later.

Module on

The above generated their own project, but I am still here to analyze my set of template code to analyze.

| - API this folder manually generated directly, all of the interface code to handle on this | - | bin project executive file - WWW with one parameter, you can manually modify the port number you want, directly behind the change in the port3000Because the project default is3000Port | - config also manually create the file, database configuration information is written project | - | node_modules rely on library - public static files are placed in the inside, such as some third-party libraries what | - routes routing file, Each URI call interface function | - utils to manually create, encapsulates some commonly used tools function, easy to use | - views there is view code, I didn't use | -- app. Run the main entrance of file | js project -- package. Json engineering some of the configuration informationCopy the code

First, configure the database configuration information file of the config project. Then, some files under the utils folder can be directly tested. They are all packaged and there is no more to talk about. Views and public folder we can not use for the moment, because we do not do web development, just purely build a background.

Main modified code in app.js, API folder, routes folder.

1. API core code

First of all, API folders are analyzed and explained. Under this folder, the Hello /test folder and baseapi.js are created. This JS file is mainly on the database operation code is encapsulated, you can not see, wait to see all the code below the two folders will find that this code is very similar to those, but I wrapped him.

In the hello folder, there is a JS file, write two functions hello1, hello2, the main function is to query the data in the database, and then return to the front end. When you import your own database configuration file, you can find that DBConfig has an @ symbol in front of it. This symbol represents the root directory of the project, from which you get the information about this file. This is a bit like Vue, but we need to configure it ourselves. See the article “Node Project uses @ instead of root” to see how to do this.

Once you’ve done these two functions, be sure to write the following code, export the two functions, and then you’re done.

module.exports = {
    hello1,
    hello2
};
Copy the code

The same goes for the testapi.js file under the test folder, which is used to insert and modify the database. I’m not going to analyze them all.

There is also a testapi_2.js file in the test folder, which does the same thing as helloapi.js in just a few lines of code. This is to call the functions wrapped in baseapi.js, which is much easier to develop later.

After the back-end function is written, here is how to explain the front-end request.

2. Route configuration

Front-end request back-end data is through the URL address to request, we write the above function is to the front-end to request, only the front-end issued a request, then the back-end will call a piece of code to execute him.

So how do you set this URL. First said briefly about the composition of the URL, as one of the project interface address for http://localhost:8000/api/hello/hello1, generally in the browser can do not need to enter http://, because the browser will automatically completion. Localhost is the local IP address, which can be changed to 127.0.0.1, or check the local LAN IP address. I changed the port number from 3000 to 8000 before, which is configured by myself. If it is a directly generated project, the default is 3000. / API /hello/hello1 is the interface address we set ourselves.

We use routes/hello.js as an example. Start by importing the modules needed for routing. Then import the function written above to him, here directly import the file path can be. Then set whether it is a GET request or a POST request, what the request path is, and which function that path corresponds to. Finally, export this module, because we only set the last path, we will need this module later.

// Import modules
var express = require('express');
var hello = express.Router();
// Import the written function
var helloApi = require('@/api/hello/helloAPI')
// Set the interface path, where post indicates that the request sent by the front end must be POST request, if it is GET, then this function will not be called for a long time. Of course, we can change post to GET if we want. Then the first parameter is the representative of a request address, the address is http://localhost:8000/api/hello/hello1 and the path is a hello1 above, then the corresponding function is hello1 this function, that is to say, the front if the request is hello1 this path, So the function that gets called in the background is hello1.
hello.post('/hello1', helloApi.hello1);
hello.post('/hello2', helloApi.hello2);
// Export this module
module.exports = hello;
Copy the code

3. Main entry file (app.js)

The above explained how to set up the interface, and then which interface to call which function, this is our own rules. All we have to do is tell the front end what the interface is, and he can just ask for it, without knowing how it’s implemented in the background.

In app.js, find the code for setting the route. This module is the address of the interface exposed to the front-end request. Inside the other detailed code I will not explain the same, I have written a note, you can view one by one.

/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- set the routing -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
app.use('/api/test'.require('./routes/test'));
app.use('/api/hello'.require('./routes/hello'));
Copy the code

Here the first parameter to mean that the same as above, artificial regulation well path, because the code is below the API folder, and then each folder set different interface address for him, is named folder name the address of the interface, this facilitate our management, a see will know call the function, then an error or maintenance.

The second parameter is to import the route file just now. We also define an interface address hello1 in the route file, where we set the function name to be called and the folder to be called in app.js, so that the level by level specification is convenient for later maintenance and team cooperation. Hello1 = hello1 = hello1 = hello1 = hello1 = hello1 / API /hello/hello1, the front-end can just request this address to get the data.

4. Solving problems beyond

When we request data, we may encounter cross-domain problems, and the console will report such errors.

Access to XMLHttpRequest at 'http://localhost:8000/api/hello/hello1' from origin 'http://localhost:8000
Copy the code

This is a cross – domain problem. Cross-domain, as the name implies, is across two different domain names, browsers think that any three different IP, port, protocol is a different domain, so you have to solve this problem. Add the following code in app.js, and you can solve the problem perfectly.

/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- set the cross-domain request -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
app.all(The '*'.function (req, res, next) {
  res.header("Access-Control-Allow-Origin"."*");
  res.header('Access-Control-Allow-Headers'.'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By".'3.2.1')
  res.header("Content-Type"."application/json; charset=utf-8");
  next();
});
Copy the code

The request data

After deploying the back end above, perfect can write a web page to request data in the front end. In the Views project, I wrote a simple web page with an input field and a button to send requests back to the backend.

    $(".btn").on("click".function(){
        // This is the address of the interface.
        // To call the hello1 interface, write /hello/hello1 in the input field
        // Call the hello2 interface, say /hello/hello2? Emp_sex =1, which takes a parameter because the back end sets the parameter to query the database
        var inputText = $('#in').val();
        $.post({
            url: "http://localhost:8000/api"+inputText,
            success: function(res){
                // Data is returned on success and printed on the console
                console.log(res)
            },
            error: function(res){
                console.error("Error",res)
            }
        })
    })
Copy the code

To this, this set of templates on the analysis of the end, if you do not understand the partner can leave a message below.