Node.js--(express framework)

1. Basic introduction

Express is a fast, open and minimalist web development framework based on Node.js platform

  • web development: display pages for different requests; Provide interface services;

  • Framework is a semi-finished product, which is used to quickly solve a class of problems; Framework: bootstrap, lay UI, express, Vue;

  • A library is a tool set that completes specific functions by calling APIs. Libraries: zepto.js, jQuery, day.js, react, underscore, lodash, art template, Axios, echart

main points:

understand:

  • We used the http module to support web services and write the interface - native js

  • Now we need to use express to write the web service and the interface ---- jQuery

  2. Managed static resources - web server

2.1 objectives  

Static middleware is used to host static resources and realize web server

Reference documents

Allowing users to directly access static resources is the most basic function of a web server.

http://localhost:3000/1.png
http://localhost:3000/css/style.css
http://localhost:3000/js/index.js

For example, the above URLs are to request an image, a style file, and a js code. The web server we implement needs to be able to directly return the contents of these files to the client browser.

When we studied the http module earlier, we have implemented these functions, but we have to write a lot of code. Now we can use the express framework with only one sentence of code, which is express.static('directory ')

2.2 basic use  

// Load Express
const express = require('express')

// 1. Call express() to get an app
//    Similar to http.createServer()
const app = express();

// 2. Static resource hosting
app.use(express.static('public'))


// 3. Listen for the port number and start the Web service
app.listen(3000, () => console.log('app listening on port 3000!'))

At this time, all contents placed under public can be accessed directly. Note that public directories do not need to appear in the url at this time

  • Create a new index.html under public, which can be accessed directly.

2.3 restricted prefix  

// Restricted access prefix
app.use('/public', express.static('public'))

  This means that if you want to access the content under public, you must add / public to the request url

3. Write interface - get interface has parameters  

3.1 objectives  

Learn the req.query attribute and write the get interface with parameters as required  

3.2 req.query attribute  

The express framework will automatically collect the query string parameters passed from the url address by the get method and automatically save them in the query attribute of the req object. We can get it directly.  

app.get('/get', function(req, res) {
  // Direct return object
  console.log(req.query);
});

  3.3 requirements

const express = require('express');
const app = express();
app.get('/get', function(req, res) {
  // Direct return object
  console.log(req.query);
  res.send({ name: 'abc' });
});
app.listen('8088', () => {
  console.log('8088');
});

  3.4 summary

The req.query property is an additional property provided by the express framework.  

4. post interface -- common key value pair parameter  

4.1 objectives  

Use express.urlencoded() to get the parameters of the request body.

Specifically, when the content type is x-www-form-urlencoded, it indicates a common simple key value pair uploaded.

4.2 definition of back-end interface  

// 1. Use middleware
app.use(express.urlencoded());

app.post("/add",function(req,res){
    //2. You can get the key value pair passed by post through req.body	
    res.json(req.body)

})

be careful:

  • After app.use(...), there will be an additional attribute res.body in res.body.

4.3 postman test  

 

  5. post interface -- parameters in json format

5.1 objectives

Use express.json() to get the json data passed in the request body.

5.2 back end

app.use(express.json());
// The req.body attribute will be automatically added, which contains the parameters passed in by the post request

// Used to process JSON formatted data
app.post('/postJSON',(req,res)=>{
    // Back end receives post parameter
    console.log(req.body);
    
    res.send('/postJSON')
})

  When passing parameters through post, if the parameters to be passed in are complex (multi-level nesting), you can upload them in json format.

var data = {
 name:"abc",
 address:{
     "a":1,
     "b":2,
     "info":"c"
 }
}

  5.3 postman operation

 

6. post interface -- form data file upload  

6.1 objectives

Learn to use the third-party package multer to realize the file upload function

6.2 multer

Multer is a node.js middleware, which is used to process multipart / form data form data. It is mainly used to upload files.

If the file upload operation is involved, the third-party multer package (not belonging to express) needs to be used on the server to obtain the uploaded information.

6.3 back end  

1. Installation

npm install multer

2. Use

// 1. Introduction package
const multer = require('multer');
// 2. Configuration
const upload = multer({dest:'uploads/'}) // The uploaded files will be saved in this directory
// uploads represents a directory name, and you can also set it to other directories

// 3. Use
// This route uses the second parameter. upload.single to indicate single file upload, and 'cover' to indicate the key name of the file to be uploaded in the last data this time. Corresponding to the on the front page:
//  <input type="file" name='cover'/>

app.post("/postfile", upload.single('cover'), function(req,res){
    // req.file records the information of file upload
    // req.body records the information of other common parameters (not files)
	// Other operations
})

explain:

  • If there are no uploads in the current directory, it will automatically create the uploads folder

  • upload.single only handles the upload of files. You can still get other parameters through req.body

6.4 postman test  

The operations corresponding to postman are as follows:  

 

7. Understand interface parameters  

 

7.1 request message: line, header and body

We generally use ajax technology to request interfaces. According to the agreement of http protocol, each request has three parts:

  • Request line: saves the request method and address, and a small part of data can be attached in the format of query string.

  • Request header: it can attach a lot of information. Content type is used to specify the data format saved in the request body.

    Content type has three common values:

 

  • Request body: parameters carried in this request. How these parameters should be parsed at the back end depends on the content type in the request header.  

8. RESTful interface  

Is a way of designing interfaces. RESTful design is:

  • Design resources by URL. Interface names are generally nouns and do not contain verbs.

  • The request mode (get,post,delete,put) determines the operation type of resources

8.1 common interface design

  • Only get and post interfaces are used

  • The address of the interface is generally composed of verb + noun

  • The address of each interface is different

For example:

Interface name: localhost:8080/getarticle type: get function: get article information

Interface name: localhost:8080/addarticle type: post function: add new article

Interface name: localhost:8080/delarticle type: post function: delete article

Interface name: localhost:8080/updatearticle type: post function: edit article

//------------The following is a common api design---------------

app.get('/getarticle',(req,res)=>{
    res.send('obtain')
})

app.post('/addarticle',(req,res)=>{
    res.send('add to')
})

app.post('/delarticle',(req,res)=>{
    res.send('delete')
})
app.post('/updatearticle',(req,res)=>{
    res.send('edit')
})

  8.1 RESTful interface design

The difference between the above functions mainly depends on the interface name and request type. In restful design, they should be as follows:

Interface name: localhost:8080/articles type: get function: get article information

Interface name: localhost:8080/articles type: post function: add new articles

Interface name: localhost:8080/articles type: delete function: delete articles

Interface name: localhost:8080/articles type: put function: edit article

RESTful design is:

  • Design resources by URL. Interface names are generally nouns and do not contain verbs.

  • The request mode (get,post,delete,put) determines the operation type of resources

8.3 reference code  

const express = require('express')

const app = express();

app.get('/articles',(req,res)=>{
    res.send('obtain')
})

app.post('/articles',(req,res)=>{
    res.send('add to')
})

app.delete('/articles',(req,res)=>{
    res.send('delete')
})
app.put('/articles',(req,res)=>{
    res.send('edit')
})

app.listen(8080,()=>{
    console.log(8080); 
})

Tags: Javascript node.js

Posted on Tue, 14 Sep 2021 21:16:21 -0400 by cjmling