Node.js --- using Express write interface

Posted by bftwofreak on Wed, 12 Jan 2022 11:10:03 +0100

1, Create basic server

As follows:

//Import Express module
const express = require('express')
//Create a server instance of Express
const app = express()

//Call app Listen method, specify the port number and start the server
app.listen(80,function(){
	console.log('Express server running at http://127.0.0.01')

2, Create API routing module

As follows:

//apiRouter.js [routing module]
const express = require('express')
const apiRouter = express.Router()
// ...
moudle.exports = apiRouter
//------------------------------------
//app.js [import and register routing module]
const apiRouter = require('./apiRouter.js')
app.use('/api',apiRouter)

3, Write GET interface

As follows:

apiRuter.get('/get',(req,res)=>{
	//Get the data sent to the server by the client through the query string
	const query = req.query
	//Call the res.send () method to respond the data to the client
	res.send({
		status:0,			//Status, 0 indicates success and 1 indicates failure
		msg:'GET Request succeeded'), //State description
		data:query		  // Specific data to be responded to the client
	})
})	

Open the server at the terminal, start it, and test it in postman, including:

Next, you can dynamically enter the parameters to query, as follows:

4, Write POST interface

apiRuter.post('/post',(req,res)=>{
	//Get the data sent to the server by the client through the query string
	const body = req.body
	//Call the res.send () method to respond the data to the client
	res.send({
		status:0,			//Status, 0 indicates success and 1 indicates failure
		msg:'GET Request succeeded'), //State description
		data:body		  // Specific data to be responded to the client
	})
})	

Open the server at the terminal, start it, and test it in postman, including:

Next, you can dynamically enter the parameters to query, as follows:

The contents of the response are:

5, CORS cross domain resource sharing

1. Cross domain problem of interface

There is a serious problem with the GET and POST interfaces just written: cross domain requests are not supported. The verification is as follows:
Create an html file as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.min.js"></script>
</head>
<body>
<button class="btn1">get request</button>
<button class="btn2">post request</button>
<script>
  $(function(){
    //Test get request
    $('.btn1').on('click',function(){
      $.ajax({
        type:'GET',
        url:'http://127.0.0.1/api/get',
        data:{name:'Wang Huan',age:18},
        success:function(res){
          console.log(res)
        }
      })
    })
    //Test post request
    $('.btn2').on('click',function(){
      $.ajax({
        type:'POST',
        url:'http://127.0.0.1./api/post',
        data:{bookName:'You are the April day on earth',
          author:'Lin Huiyin'
        },
        success:function(res){
          console.log(res)
        }
      })
    })
  });
</script>
</body>
</html>

Open the browser to run, including:

An error is found, which is caused by a cross domain problem. The page I opened was in
There are two main solutions to interface cross domain problems:

  • CORS (mainstream solution, recommended)
  • JSONP (defective solution: only GET requests are supported)

2. Using cors middleware to solve cross domain problems

cors is a third-party middleware of Express. Cross domain problems can be easily solved by installing and configuring cors middleware.
The use steps are divided into the following three steps:
(1) Run npm install cors to install the middleware

(2) Import middleware using const cors = require('cors')
(3) call app. before routing. Use (cors()) configuration Middleware
After the configuration is completed, run the test interface to solve the cross domain problem html, as follows:

Cross domain request succeeded.

3. What is CORS

CORS (cross origin resource sharing) consists of a series of HTTP response headers, which determine whether the browser prevents the front-end JS code from obtaining resources across domains.
The browser's same origin security policy prevents web pages from "cross domain" access to resources by default. However, if the interface server is configured with CORS related HTTP response headers, the cross domain access restrictions on the browser side can be lifted. As shown in the figure below:

However, it should be noted that:

  • CORS is mainly configured on the server side. The client browser can request to open the CORS interface without any additional configuration.
  • CORS is compatible in browsers. Only browsers that support XMLHttpRequest Level 2 can normally access the server interface with CORS enabled (e.g. IE10 +, Chrome4 +, Firefox 3.5 +).

4. CORS response header - access control allow origin

An access control allow origin field can be carried in the response header. Its syntax is as follows:

Access-Control-Allow-Origin:<origin>|*

The value of the origin parameter specifies the foreign domain URL that is allowed to access the resource. For example, the following field values will only be allowed from http://www.cn Request for:

res.setHeader('Access-Control-Allow-Origin','http://www.cn')

If the value of access control allow origin field is specified as wildcard *, it indicates that requests from any domain are allowed, as follows:

res.setHeader('Access-Control-Allow-Origin','*')

5. CORS response header - access control allow headers

By default, CORS only supports the client to send the following 9 request headers to the server:
Accept, accept language, content language, DPR, Downlink, save data, viewport Width, Width, content type (values are limited to one of text/plain, multipart / form data, application/x-www-form-urlencoded).
If the client sends additional request header information to the server, you need to declare the additional request header on the server through access control allow headers, otherwise the request will fail!

res.retHeader('Access-Control-Allow-Headers','Content-Type,X-Custom-Header')

It should be noted that multiple request headers should be separated by English commas.

6. CORS response header - access control allow methods

By default, CORS only supports GET, POST and HEAD requests initiated by the client.
If the client wants to request the server's resources through PUT, DELETE, etc., it needs to indicate the HTTP method allowed for the actual request through access control alow methods on the server side.

//Only post, get, delete and head request methods are allowed
res.setHeader('Access-Control-Allow-Methods','POST,GET,DELETE,HEAD')
//Allow all HTTP request methods
res.setHeader('Access-Control-Allow-Method','*')

7. Classification of CORS requests

When the client requests the CORS interface, according to the different request methods and request headers, the CORS requests can be divided into two categories: simple requests and pre check requests.

1. Simple request

A request that meets both of the following two conditions is a simple request:
(1) Request method: one of GET, POST and HEAD
(2) The HTTP header information does not exceed the following fields: no custom header field, Accept, Accept language, content language, DPR, Downlink, save data, viewport Width, Width, content type (only three values: application/x-www-form-urlencoded, multipart / form data, text/plain)

2. Pre inspection request

As long as the request meets any of the following conditions, a pre inspection request is required:
(1) Request Method types other than GET, POST and HEAD
(2) The request header contains a custom header field
(3) Data in application/json format was sent to the server
Before the browser formally communicates with the server, the browser will send an OPTION request for pre check to know whether the server allows the actual request. Therefore, this OPTION request is called "pre check request". After the server successfully responds to the pre check request, it will send the real request and carry the real data.

3. Difference between simple request and pre inspection request

Characteristics of simple request: only one request will occur between the client and the server.
Characteristics of pre check request: two requests will occur between the client and the server. The real request will not be initiated until the OPTION pre check request is successful.
As follows, we are adding a delete request as a pre check request, then adding a click event to it on the page, initiating a request through ajax, and then adding a delete interface:

<button class="btn3">delete request</button>
 $('.btn3').on('click',function(){
          $.ajax({
              type:'DELETE',
              url:'http://127.0.0.1/api/delete',
              success:function(res){
                  console.log(res)
              }
          })
      })
router.delete('/delete',(req,res)=>{
    res.send({
        status:0,
        msg:'DELETE Request succeeded',
    })
})

Open the browser to test:

You can see that in the delete request, two requests occur between the client and the server.

6, JSONP interface

It has been right in the early stage JSONP After a detailed description, here are the features of jsonp:

  • JSONP is not a real Ajax request because it does not use the XMLHttpRequest object.
  • JSONP only supports GET requests, not POST, PUT, DELETE and other requests.

1. Considerations for creating JSONP interfaces

If CORS cross domain resource sharing has been configured in the project, in order to prevent conflicts, the JSONP interface must be declared before configuring CORS middleware. Otherwise, the JSONP interface will be processed as an interface with CORS enabled. The example code is as follows:

//Create JSONP interface first [this interface will not be processed as CORS interface]
app.get('api/jsonp',(req,res)=>{
	//......
 })
//When configuring CORS middleware [all subsequent interfaces will be processed into CORS interfaces]
app.use(cors())
//This is an interface with CORS enabled
app.get('api/get'),)res,req)=>{ })

2. Steps to implement JSONP interface

(1) Gets the name of the callback function sent by the client

const funcName = req.query.callback

(2) Get the data to be sent to the client in the form of JSONP:

const data = {name:'Wang Huan',age:18}

(3) According to the data obtained in the previous two steps, splice a function call string:

const = scriptStr = `${funcName}(${JSON.stringify(data)})`

(4) Parse and execute the string spliced in the previous step in response to the < script > tag of the client:

res.send(script)

3. Initiate a JSONP request using jQuery in a web page

Call $ The ajax() function provides JSONP configuration options to initiate JSONP requests. The example code is as follows:

 $('.btn4').on('click',function(){
      $.ajax({
           type:'GET',
           url:'http://127.0.0.1/api/jsonp',
           dataType: 'jsonp',
           success:function(res){
               console.log(res)
        }
    })
})

Open the browser to test:


Successfully requested data found.

Complete code

apiRouter.js:

const express = require('express');
const router = express.Router()
//Mount the corresponding route
router.get('/get',(req,res)=>{
    //Get the data sent to the server by the client through the query string
    const query = req.query
    //Call the res.send () method to respond the data to the client
    res.send({
        status:0,			//Status, 0 indicates success and 1 indicates failure
        msg:'GET Request succeeded', //State description
        data:query		  // Specific data to be responded to the client
    })
})
router.post('/post',(req,res)=>{
    const body = req.body
    console.log(body)
    res.send({
        status:0,			//Status, 0 indicates success and 1 indicates failure
        msg:'POST Request succeeded', //State description
        data:body		  // Specific data to be responded to the client
    })
})
router.delete('/delete',(req,res)=>{
    res.send({
        status:0,
        msg:'DELETE Request succeeded',
    })
})
module.exports = router;

Use the Express write interface js:

//Import express
const express = require('express')

//Create server instance
const app = express()
app.get('/api/jsonp',(req,res)=>{
    const funcName = req.query.callback
    const data = {name:'Little bear',age:18}
    const scriptStr = `${funcName}(${JSON.stringify(data)})`
    res.send(scriptStr)
})
//Configuration Middleware
app.use(express.urlencoded({extended:false}))
const cors = require('cors')
app.use(cors())
//Import routing module
const router= require('./apiRouter')
//Register the routing module on the app
app.use('/api',router)
//Start the server
app.listen(80,function(){
    console.log('Express server running at http://127.0.0.1')
})

Test interface cross domain issues html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.min.js"></script>
</head>
<body>
<button class="btn1">get request</button>
<button class="btn2">post request</button>
<button class="btn3">delete request</button>
<button class="btn4">JSONP request</button>
<script>
  $(function(){
    //Test get request
    $('.btn1').on('click',function(){
      $.ajax({
        type:'GET',
        url:'http://127.0.0.1/api/get',
        data:{name:'Wang Huan',age:18},
        success:function(res){
          console.log(res)
        }
      })
    })
    //Test post request
    $('.btn2').on('click',function(){
      $.ajax({
        type:'POST',
        url:'http://127.0.0.1/api/post',
        data:{bookName:'You are the April day on earth',
          author:'Lin Huiyin'
        },
        success:function(res){
          console.log(res)
        }
      })
    })
      $('.btn3').on('click',function(){
          $.ajax({
              type:'DELETE',
              url:'http://127.0.0.1/api/delete',
              success:function(res){
                  console.log(res)
              }
          })
      })
      $('.btn4').on('click',function(){
          $.ajax({
              type:'GET',
              url:'http://127.0.0.1/api/jsonp',
              dataType: 'jsonp',
              success:function(res){
                  console.log(res)
          }
          })
      })
  });
</script>
</body>
</html>

Topics: Javascript node.js Front-end