Create a basic server
//Import the express moduleconst express =require('rexpress') //Create an express server instanceconst app=express() .... //Call the method, specify the port number and start the web server(80,function(){ ('server running at http://127.0.0.1'); })
Create API routing module
// var express=require('express') //Import expressvar apiRouter=() //Create a routing object=router //Export object outward// const apiRouter=require('./apiRouter') ('api',apiRouter)
Writing a GET interface
('/get',(req,res)=>{ //1. Get the data sent to the server by querying the string to the clientconst query= //2. Call the() method to respond to the data to the client ({ status:0, //Status, 0 means success 1 means failure msg:'GETRequest succeeded, // Status Description data:query //The data that needs to be responded to the client }) })
Writing a POST interface
('/post',(req,res)=>{ //1. Get the data sent to the server by querying the string to the clientconst body= //2. Call the() method to respond to the data to the client ({ status:0, //Status, 0 means success 1 means failure msg:'POSTRequest succeeded, // Status Description data:body //The data that needs to be responded to the client }) })
Before getting the route, you need to configure the middleware for parsing the form
//Configure middleware for parsing form data(({extended:false}))
CROS cross-domain resource sharing
1. Cross-domain issues of interfaces
There is a very serious problem with the GET and POST interfaces I just wrote: cross-domain requests are not supported. There are two main solutions to solve the cross-domain problem of interfaces
- CORS (mainstream solution, recommended) CORS (mainstream solution, recommended)
- JSONP (Flawed Solution: Only GET Requests) Flawed Solution: Only GET Requests
2. Reject cross-domain issues using cros middleware
cros is a third-party middleware for Express. By installing and configuring cors middleware, cross-domain problems can be easily solved
Steps to use
- Run npm install cros installation middleware
- Import middleware using const cros=require('cros')
- Call (cros()) before routing to configure middleware
3. What is cros
cros (Cross-Origin Resource Sharing, Cross-Domain Resource Sharing) consists of a series of HTTP response headers that determine whether the browser prevents front-end JS code from obtaining resources across domains.
The browser's homologous security policy will block web pages from "cross-domain" or missing resources by default, but if the interface server is configured with CROS-related HTTP response headers
You can contact the browser's cross-domain access restrictions
Things to note
- Cros is mainly configured on the server side. The client browser does not need to make any additional configuration to request the cros interface to be enabled.
- Cros has compatibility in browser.
Requested classification
When a client requests the cors interface, according to the different request method and request header, cross-domain divides cros requests into two categories, namely:
- Simple request
- Request method: GET, POST, HEAT
- HTTP header information does not exceed the following fields: no custom header, Accept, Accept-Language, Content-Language, DPR, Dpwnlink, Sava-Data, Viewport-Width, Width, Content-Type
- Pre-check request
- The request method is a request method type other than GET, POST, and HEAD
- Request header contains custom header fields
- Send application/json format data to the server
Before the browser and the server officially communicate, the browser will send an OPTION request for pre-checking to obtain whether the browser allows the actual request. Therefore, this time the OPTION request is a "pre-check request". Only after the server successfully responds to the pre-checking request will the real request be sent and the real data will be carried.
6. The difference between simple request and pre-check request
Features of simple requests: Only once request occurs between the client and the server.
Features of pre-flight requests: Two requests will occur between the client and the server. Only after the OPTION pre-flight request is successful will the real request be initiated.
JSONP interface
1. Review the concepts and characteristics of jsonp
Concept: Browser via/
Features:
- JSONP does not belong to ajax request because it does not use the XMLHttpRequest object
- JSONP only supports GET requests, not POST, PUT, DELETE and other requests
2. Things to note when creating a jsonp interface
If the cross-domain resource sharing of CROS has been configured in the project, in order to prevent conflicts, the JSONP interface must be declared before configuring the CROS middleware, otherwise the JSONP interface will be processed to enable the CROS interface.
3. Steps to implement the JSONP interface
- Get the name of the callback function sent by the client
- Get the data to be sent to the client through JSONP ()
- Based on the data from the previous two steps, splice out a string of function calls
- Response the string obtained from the previous step to the client's /
4. Specific code for implementing JSONP interface
('/api/jsonp',(req,res)=>{ //Get the name of the callback function sent by the client const funcName= //Get the data to be sent to the client through JSONP const data={name:'zs',age:22} //Split a string of function calls based on the data obtained in the previous two steps const scriptStr=`${funcName}(${(data)})` //Response the splicing string obtained in the previous step to the client's <script> tag for parsing (scriptStr) })
5. Use jq to initiate a jsonp request on the web page
Call $.ajax() to provide JSONP configuration request, thereby initiating JSONP request
$("#btnJSONP").on("click", function () { $.ajax({ type: "GET", url: "http://127.0.0.1/api/jsonp", dataType: "jsonp", success: function (res) { (res); }, }); });
This is the end of this article about writing interfaces using express. For more information about writing interfaces using express, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!