I. Express foundation

Express: nose.js Web application framework

/ / modules
const express = require('express');
const bodyParser = require('body-parser');
// Create a service
const app = express();
const port = 8686;
app.listen(port,()=>{
    //=> create a service => listen to the port and later request to execute the app method
    console.log(`server is success,listen on ${port}! `)});// Static resource file processing
/ / the browser enter localhost: 8686 / index. HTML
app.use(express.static('./static'));
Copy the code

Middleware in Express

When the client sends a request to the server, if the request is get and the request path is ‘./ getName ‘, the callback function is triggered with three parameters (req,res,next).

1) Parameter 1: REQ

Not a native Node reQ, it is encapsulated by the Express framework, but it also stores many objects passed by the client

  • req.paramsPath parameter information is stored
  • req.pathThe requested path name
  • req.queryRequest question mark pass-through information (GET request) (object)
  • req.bodyWhen the request is posted and processed by the Body-Parser middleware, the content passed from the client request body is stored in the Body attribute
  • req.sessionAfter processing based on express-Session middleware, session operations will be placed on this property, based on which session information can be manipulated
  • req.getGets the specified request header information
  • req.paramThis method is used to retrieve information corresponding to a property name in the urL-encoded string (or path parameter)

2) Parameter 2: RES:

Provides properties and methods that the server can use to return content to the client

  • res.cookie()You can set some cookie information, through the response header set-cookie returned to the client, the client returned Xookie information to the local
  • res.json()Returns a string in JSON format to the client, but allows us to pass in a JSON object, which is converted to a string and then returned.
  • res.redirect()The response is redirected to status code 302
  • res.send-status()Set the returned status code to end the response, and return the information corresponding to the status as the body of the response, usually using status. Then set the body content of the response yourself
  • res.type()Sets the MIME type of the corresponding content
  • res.status()Set the response status code
  • res.sendFile(path)Fetching the contents of the file specified by path and returning the contents to the client browser (after the file is read and the response is completed) also automatically ends the response
  • res.send()Return anything
  • res.set()Setting the response header

3) middleware

  • Req.query/req.param()

  • Post requests, which receive information passed by the request body, require a middleware body-Parser

  • Middleware: before API interface request processing, extract some common parts, middleware is to deal with these common content first, after the completion of processing, continue to execute the interface request

/ / middleware
app.use('/user',(req,res,next)=>{
    // Request a path address that begins with/XXX, e.g. '/user' '/user/add'
    next(); You can't go to write a middleware or request without executing next
});
app.use((req,res,next) = >{
    // All requests go through this middleware, and the middleware executes in written order
    next();
});

/ / API
app.get('./getname',(req,res)=>{
    res.send({
        message: 'ok'
    }); 
})

// body-parser; In the case of a POST request, the information passed based on the request body is pre-intercepted
// If you pass a JSON-formatted string, the body-parser method converts it to a JSON-formatted object
// If a urL-encoded string is passed, it is converted to an object key-value pair
// Mount the transformed result to the req.body property
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/user',(req,res)=>{
    console.log(req.body); // The request body is an object {XXX :xx, XXX :xx}
})
Copy the code

Routes in Express

In real projects, in order to effectively manage interfaces, we will classify interfaces of the same functional system and implement them in different categories (group management). For example:

/user/signin

/user/signup

/product/query

/product/search

/log/info => GET Obtains the POST Settings

The same address because the request is not the same, to achieve different functions

This kind of operation can be done based on routes in Express

  • 1) Create an interface folder for all functional modules and store the interface information in this folder.
  • 2) Write API interfaces in each routing module (example: User module)
   let express =require('express');
   let router = express.Router();
   Router is similar to app in that it has the function of route management
   // Middleware (usually written before interface)
   router.use((req,res,next) = >{
       console.log('ok');
       next();
   })
   router.post(`/signin`,(req,res)=>{
       res.send('Successful landing');
   })
   router.post(`/signup`,(req,res)=>{
       res.send('Registration successful');
   })
   // Place the created route everywhere for later retrieval
   module.exports = router;
Copy the code
  • 3) Use it in server.js
   const express = require('express');
   const app = express();
   
   // Import routes
   app.use(`/user`.require('./routers/user'));
   app.use(`/log`.require('./routers/log'));
Copy the code