A brief introduction to HTTP module
HTTP built-in modules in Node.js can be used to create HTTP servers and HTTP clients. const http = require(‘http’);
1.1. Create an HTTP server
Although the HTTP core module in Node.js can be used to implement a Web server, it does a lot of work, such as detecting the content type of each file, so we decided to use the Connect module, on which the popular Express Web framework is built.
var server = http.createServer((req,res)=>{
});
Copy the code
The.createserver () method using HTTP can be used to return an HTTP server instance, which is received with a custom server variable. The server invokes its internal callback function every time it receives a request from a client, and every time the client accesses it, it invokes it. The callback function takes two arguments, req and res, which cannot be reversed. Req stands for request and res stands for response.
This callback must contain res.end(); If not, the browser will assume that it has not received any response from the server, and the browser will remain suspended. In this case, the browser has an internal timeout mechanism, and will report an error if it times out.
Common code statements in this callback are: Set the response header, res.writehead (status code,{}); The HTTP status code is commonly used 200 (successfully returned), 404 (can not find the page, return error) and so on. The second argument passes in an object that sets the render parsing type of the response text. For HTML code, res.writehead (200,{" content-type ":"text/ HTML; charset=UTF8"}); For CSS files set to res.writehead (200,{" content-type ":"text/ CSS "}); For images set res.writehead (200,{" content-type ":"image/ JPG "}); For plain text, set res.writehead (200,{" content-type ":"text/plain"}); Set what is returned, res.write(");
1.2. Have the server listen for a specific port number
A custom variable server is used to represent the server to be created to listen for a specified port number. Server. Listen (3000, ‘127.0.0.1); External clients can access the server using this IP address and port number.
In this case, the server is suspended. In this case, enter the corresponding IP address and port number in the browser to obtain the response from the server.
1.3. Complete sample code:
const http = require('http'); const url = require('url'); const qs = require('qs'); var server = http.createServer((req,res)=>{ const { method} = req; res.writeHead(200,{"Content-Type":"text/html; charset=UTF8"}); res.write('hello world'); // const urlJson = url.parse(req.url); // var query = qs.parse(urlJson.query); // console.log(query); const urlJson2 = url.parse(req.url,true); console.log(urlJson2.query) if (method == "GET" && url == "/users") { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify([{ name: "tom", age: 20 }])); } res.end(); }); server.listen(3001); console.log('listen 3001');Copy the code
Observe the HTTP protocol and its history
curl -v www.baidu.com
HTTP history:
version | Have the time | content | Current situation of the development of |
---|---|---|---|
HTTP / 0.9 | In 1991, | Does not involve data packet transmission, specifies the communication format between the client and server, can only GET request | Not as a formal standard |
HTTP / 1.0 | In 1996, | You can add the PUT, PATCH, HEAD, OPTIONS, and DELETE commands | Formally as a standard |
HTTP / 1.1 | In 1997, | Persistent connection (long connection), bandwidth saving, HOST field, pipeline mechanism, block transfer coding | It was most widely used before 2015 |
HTTP/2 | In 2015, | Multiplexing, server push, header compression, binary protocol, etc | Gradually covering the market |
Multiplexing: Multiple request-response messages are sent from a single HTTP/2 connection request, and multiple request streams share a TCP connection, enabling multiple connections in parallel rather than relying on the establishment of multiple TCP connections.
2.1 Pipelining mechanism
HTTP 1.1 introduced Pipelining, which allows clients to send multiple requests simultaneously over the same TCP connection. If the client needs to request two resources, it sends A request to the same TCP connection and waits for the response from the server. After receiving the request, it sends A request to the server. The pipeline mechanism allows the browser to make both A and B requests at the same time, but the server responds to A and B requests in the same order.
2.2 What is multiplexing?
In HTTP 1.0, to initiate a request, the browser requests a URL -> resolves a domain name -> establishes an HTTP connection -> the server processes a file -> returns data -> the browser parses and renders a file
This process is the biggest problem is, every request need to build a HTTP connection, namely we often say three times handshake wave four times, the process in a quite a long time in the process of request and logically is required, because of the continuous request data, first establish a connection is normal, then takes up the channel, Download other files. How efficient!
To address this, HTTP 1.1 provides keep-alive, which allows us to establish a single HTTP connection to return multiple requests.
Although HTTP 1.1 enables long TCP connections by default, all request-response is sequential (long connections here can be understood as the half-duplex protocol). This is true even when HTTP 1.1 introduced pipelines). During the reuse of the same TCP connection, even if multiple requests are sent through the pipeline at the same time, the server responds in sequence according to the request sequence. A client blocks subsequent requests (queuing) until it receives a response for all previous requests, which is called “head-of-line blocking.”
HTTP/2 multiplexed TCP connections, on the other hand, still follow the request-response pattern, but there is no limit to the order in which the client can send multiple requests and the server can send multiple responses, thus avoiding “queue congestion” and getting responses faster. When reusing the same TCP connection, the server receives two requests (A and B) at the same time (or successively), and responds to A request first. However, as the processing process is time-consuming, the server sends the processed part of A request, responds to B request, and then sends the remaining part of A request. HTTP/2 long connections can be understood as full-duplex protocols.
HTTPS protocol
HTTPS: hypertext transfer security protocol
Is a transport protocol for secure communication over computer networks. HTTPS communicates over HTTP, but uses SSL/TLS to encrypt packets. HTTPS is developed to provide identity authentication for web servers and protect the privacy and integrity of exchanged data. The protocol was first proposed by Netscape in 1994 and then extended to the Internet.
Simply put, HTTPS is a secure version of HTTP that uses SSL/TLS encryption. Authentication, information encryption and integrity verification through TLS/SSL protocol to avoid the risk of information eavesdropping, information tampering and information hijacking.
- Secure Socket Layer (SSL) Indicates the Secure Socket Layer
- Transport Layer Security (TLS) Transport Layer Security
3.1 What is HTTPS?
In the illustrated HTTP book, HTTPS is HTTP in an SSL shell. HTTPS is a transport protocol for secure communication over the computer network. It uses SSL/TLS to establish full-channel communication and encrypt data packets. The primary purpose of HTTPS is to provide identity authentication to web servers and protect the privacy and integrity of the data exchanged.
PS:TLS is a transport layer encryption protocol, formerly SSL, released by Netscape in 1995.
HTTPS provides Encryption, authentication, and Identification
- Privacy (Confidentiality/Privacy) :
That is to provide information encryption to ensure the security of data transmission; Make sure the information stays with Joe and Joe, and it won’t be bugged.
- Credibility (Authentication) :
Authentication, mainly on the server side, verifies the authenticity of the website. Some banks also authenticate the client side. To prove that Leo is Leo.
- Message Integrity:
Ensure the integrity of information transmission process, prevent modification; Joe sent the message that Joe received. HTTPS adds an authentication barrier between the application layer and the transport layer to ensure data security
3.2 the SSL/TLS
Secure Socket Layer (SSL) :
SSL protocol was developed by Netscape corporation, the first version was not released; The second version was released in November 1994, but failed; Version 3 SSL (V3) was released in 1995. SSL3 has been successful and has been phased out in recent years.
Transport Layer Security (TLS) : In May 1996, the TLS Working Group of the International Organization for Standardization migrated SSL from Netscape to IETF. TLS 1.0 was introduced in January 1999, although the changes were minor compared to SSL 3; April 2006 TLS 1.1 release; TLS1.2 was released in August 2008; The TLS version 1.3 was planned around 2014, and the TLS version was completed on March 21, 2018. However, it is not widely used, and the support and services are not well developed. The most widely used is TLS1.2.
When the Internet was first designed, information security was not taken into account, making communication itself insecure. So TLS was developed to realize encrypted transmission and ensure information security.
3.3 Why Is SSL Configured?
Due to IPV4 proxy and various network routing technologies, HTTP domain names may be hijacked in some areas or networks. For example, some inexplicable advertisements appear when opening the web page, and click the page to jump to other third-party websites. To reduce hijacking, HTTPS is essential, and SSL certificates should be a mandatory buff for every website. Reference: www.yimenapp.com/ssl.html
HTTP “calls” the encryption algorithms in SSL/TLS to secure the transport. HTTPS is only an application-layer protocol. SSL encrypts HTTP content and uses port 443 for transmission by default. SSL also encrypts Email using ports 995 and 465 by default. Any application layer protocol (HTTP, SMTP, FTP, etc.) can “call” TLS/SSL to encrypt its plaintext data. So the simple and effective summary is: HTTPS = HTTP + SSL/ TLS
3.4 11 Differences between HTTP and HTTPS
HTTPS has become the trend, but the difference between HTTPS and HTTP is not particularly clear, this article uses a table to tell you HTTPS compared to HTTP advantages.
http | VS | https |
---|---|---|
Plaintext transmission, data interaction between websites or related services and users without encryption, easy to be monitored, cracked or even tampered with. | transport | Add SSL layer under HTTP, is the data transmission into encryption mode, so as to protect the privacy and integrity of the exchange data, simply put, it is the secure version of HTTP. |
Without any authentication, the user cannot identify the real identity of the web site through HTTP. | The identity authentication | After the CA multiple authentication, including domain name management authority authentication, corporate identity verification, etc. EV certificates can even display the company name directly in the browser address bar to improve user experience. |
There is no cost to use and all sites default to HTTP mode. | Implementation costs | You need to apply for an SSL certificate to implement HTTPS. The price ranges from hundreds to tens of thousands of yuan. For details, see SSL certificate Purchase |
Port 80 | End connections | Port 443 |
Warning: When you have a form on your site such as registration and login, Chrome will highlight “unsafe” in red as soon as the user enters: | Browser compatibility | When you apply for the “EVSSL certificate”, the browser address bar will directly display your company name, which can significantly improve the trust of website users and the image of the company |
There is no preference for HTTP sites. | SEO optimization | Baidu, Google and other official statements to increase the weight of HTTPS sites ranking. |
Easy to be hijacked by hackers or malicious peers. | Website hijacking | Privacy information is encrypted to prevent traffic hijacking |
The speed of access depends on the web site server configuration and the client’s browsing environment. | Access speed | In the same configuration of the server and client browsing environment, the page loading speed can be significantly improved. |
When a website needs to connect to a third party platform, it usually does not accept HTTP. For example, wechat mini program, Apple ATS, douyin advertising and so on. | Data docking | More and more platforms, such as wechat Mini Program, Tiktok, Apple and others, only accept encrypted secure links like HTTPS. |
The lack of HTTPS often leads to risk warnings from browsers and other platforms, damaging users’ trust. | Website image | It is the basic responsibility of a website to create a safe browsing environment for its users, as well as an important factor to win their trust. |
There is no risk protection, when the interception of website data transmission leads to significant losses, only the website operators themselves bear. | Risk guarantee | Has commercial insurance between $100,000 and $1.75 million, and has a huge amount of protection in the event of a breach of the website’s data transfer. |
4. Use NodeJS to build HTTPS Server
Create an HTTPS certificate using OpenSSL
OpenSSL is a powerful secure Socket layer password library that Apache uses to encrypt HTTPS and OpenSSH uses to encrypt SSH, but you shouldn’t just use it as a library. It’s also a versatile, cross-platform password tool.
TLS is a set of protocols and standards that encrypt data between the application layer and the transport layer. SSL/TLS is a library that implements algorithms and protocols that provide encryption functionality that is invoked by the application layer.
Openssl in Linux is an open source implementation of SSL/TLS and a variety of encryption algorithms. It implements almost all encryption algorithms and is very powerful and widely used.
OpenSSL includes: libcrypto implementation algorithm; LibssI is a session-based library that implements TLS/SSL protocol encryption and session integrity. You can also impersonate a certificate issuer using OpenSSL, whose command-line tool is OpenSSL.
mkdir https cd https openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem US Califormia Francisco Noyanse Noyanse localhost [email protected]Copy the code
Req ------> Request to create a certificate file New ------> A new certificate is created x509 ------> Define the certificate format as standard key ------> Information about the private key file for the call out ------> Information about the certificate file is output Days -------> Certificate validity period. The unit is day. The default value is 365 daysCopy the code
Index.js test code
const https = require('https');
const fs = require('fs');
const key = fs.readFileSync('./key.pem');
const cert = fs.readFileSync('./cert.pem');
const options = {
key:key,
cert:cert
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world-----\n');
}).listen(8000);
Copy the code
Reference: www.cnblogs.com/yjiu1990/p/…
V. Introduction to Connect
Connect is a Node middleware framework. If an HTTP process is like sewage treatment, middleware is like layers of filters. Each middleware realizes specific functions by rewriting the data and state of request or response during HTTP processing.
5.1 Try to be the simplest Web server
var connect = require('connect');
var app = connect()
.use(function (req, res) {
res.end('hello world\n');
})
.listen(3000);
Copy the code
5.2 the url & qs
Install NPM install URL QS or YARN add URL QS
A URL, as its name implies, is a resolution of the address requested by the client. Qs is in the URL processing results on the basis of field parsing.
const url = require('url');
const app= require('connect');
const qs = require('qs');
app()
.use(function(req, res) {
// const urlJson = url.parse(req.url);
// const query = qs.parse(urlJson.query);
const urlJson = url.parse(req.url,true);
console.log(urlJson.query.name);
})
.listen(3000);
Copy the code
6. Work mechanism of Connect
1. Custom middleware 2. Use () function supports chain call 3
In Connect, the middleware component is a function that intercepts the request and response objects provided by the HTTP server and executes the logic, either terminating the response, or passing it on to the next middleware component.
The Connect allocator calls all attached middleware components in turn until one of them decides to respond to the request, and if it knows that there is still no component at the end of the list of middleware components to respond, the program returns a 404 as a response. (Ex1 has no middleware component, so it returns a 404 Not Found status code in response to all HTTP requests it receives.)
In Connect, the middleware component is a JS function that takes three parameters
A. Request object (REQ) b. Response object (RES) c. Parameter, usually named next: a callback function indicating that the current middleware has finished executing and the next middleware component can be executed
6.1 Requirement: Simple Hello World + log
var connect = require("connect"); var app = connect() .use(logger) .use(hello) .listen(3000); function logger(req, res, next) { console.log(req.method + ' ' + req.url); next(); } function hello(req, res) {res.setheader (' content-type ', 'text/plain'); res.end("hello world"); }Copy the code
6.2 The order of middleware
var app = connect()
.use(hello)
.use(logger)
.listen(3000);
Copy the code
Hello middleware executes first and responds to HTTP requests without calling next(). Control does not return to the allocator to call the next middleware, so logger middleware does not call.
Note: When one middleware component does not call next(), no other middleware in the command chain is called.
6.3 Cross-Domain: Interface invocation problems caused by the same Origin policy of the browser
. Index. In the HTML requests in 3000 server interface axios. Get (” http://localhost:3001/users “)
Common solutions:
- JSONP(JSON with Padding), front-end + back-end solution, bypass cross-domain
The front-end constructs the SCRIPT tag request to specify the URL (GET requests made by the Script tag are not restricted by the same origin policy), and the server returns a function execution statement, the name of which is usually determined by the value of the query parameter callback, and the parameter of the function is the JSON data returned by the server. This function retrieves the data after execution in the front end. 2. The proxy server requests the same-origin server and forwards the request to the target server. The proxy function of the test server is used in the front-end development, but the final release will still cross domains if the Web application and the interface server are not together. 3. CORS(Cross Origin Resource Share) – Cross-domain Resource sharing, back-end solution, cross-domain solution Principle: CORS is a W3C specification, to solve cross-domain problems in a real sense. It allows cross-domain requests by requiring the server to examine the request and process the response header accordingly.
Concrete implementation:
- Responding to a simple request: Get /post/head, no custom headers, Content-Type is application/ X-ww-form-urlencoded, multipart/form-data, or text/plain, solved by adding the following response headers:
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3001')
Copy the code
- To respond to a preflight request, you need to respond to the options request (precheck request) issued by the browser and set the response header as appropriate:
else if (method == "OPTIONS" && url == "/users") {
res.writeHead(200, {
"Access-Control-Allow-Origin": "http://localhost:3001",
"Access-Control-Allow-Headers": "X-Token,Content-Type",
"Access-Control-Allow-Methods": "PUT"
});
res.end();
}
Copy the code
In this case, you can make the request a Preflight request by adding a custom X-Token request header
// index.html
axios.get("http://localhost:3000/users", {
headers:{'X-Token':'jilei'}
})
Copy the code
The server needs to allow x-Token, and if the request is POST, it also passes parameters:
// index.html
axios.post("http://localhost:3000/users", {foo:'bar'}, {headers:
{'X-Token':'jilei'}})
// http-server.js
else if ((method == "GET" || method == "POST") && url == "/users") { }
Copy the code
The server also needs to allow Content-Type request headers
- If cookie information is to be carried, the request becomes a credential request:
Res. setHeader(‘ access-Control-allow-credentials ‘, ‘true’) must be added to the options and /users interfaces;
Function proxy(req, res,next){function proxy(req, res,next){ http://192.168.1.29:8080 is the address res.setheader (' access-Control-allow-origin ', 'http://192.168.1.29:8080'); // res.setHeader('Access-Control-Allow-Origin', '*'); // Allow any source. If the server asks the browser to send a Cookie, This cannot be set to * res.setHeader(' access-Control-allow-methods ', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); Res.setheader (' access-control-allow-methods ', '*'); res.setHeader('Access-Control-Allow-Headers', 'X-Token,Content-Type') // res.setHeader('Access-Control-Allow-Headers', The '*'); // Allow any type of next(); // Next is a recursive call}Copy the code
7. Connect Common middleware
Connect is a very lightweight Node middleware framework. For a small to medium sized project, Connect needs to work with many third-party modules to complete the server logic. Therefore, in order to simplify the development of current projects, it is often used to upgrade express, or KOA as the base framework for extension. Of course, the most primitive details need to be studied before using these frameworks.
7.1 the body – parser
Installation: YARN add body-parser parses the request body
Node or Connect needs to parse the REQ while processing the request data. The Body-Parser middleware provides this.
- BodyParser () middleware adds a body attribute to req, which can be used to parse JSON, X-www-form-urlencoded, and multipart/form-data requests
- Body-parser only handles POST requests
- The body-Parser module exports an object with two urlencoded and JSON methods that handle form submission and JSON-formatted request body parameters, respectively
- There are also req.files objects for multipart/form-data requests, such as file uploads
- This is a very useful component, it actually integrates three other smaller components: JSON (), urlencoded(), and multipart().
- Older versions of body-Parser also handled file uploads (a file upload module like formidable is now required).
When the request body is parsed, the parsed value is placed in the req.body property. When the content is empty, Json ()– parses json format –bodyParser.raw()– parses binary format –bodyParser.text()– parses text format –bodyParser.urlencoded()– Parses text formats
const app= require('connect')(); const bodyParser = require('body-parser'); app .use(function(req, res, next) { console.log(req.body); // undefined next(); Use (bodyParser.json()) // Application /x-www-form-urlencoded; // Coded application/x-www-form-urlencoded .use(bodyParser.urlencoded({extended: true})) .use(function(req, res) { console.log(req.body); // Post request data res.end('hello world\n'); }) .listen(3000);Copy the code
Note that req.body is available for post requests, but the URL cannot be resolved through the URL
/ / as middleware form function getParamsMiddle (the req, res, next) {if (the req. Method. ToLocaleLowerCase () = = 'post') {query = the req. Body; } else { const urlJson = url.parse(req.url,true); query = urlJson.query; } req.query = query; The console. The log (' parameters'); next(); }Copy the code
Use:
. .use(getParamsMiddle) ...Copy the code
Not only connect, but body-Parser middleware is also available in Express and KOA.
7.2. The cookie – parser & jsonwebtoken
Similar to body-parser, cookie-parser converts the body of cookie requests from the browser to req.cookies. It can handle regular cookies as well as signed cookies.
Cookie and Sesssion are no longer the mainstream in the current front and back end communication, especially in the prevailing mode of third-party authentication. In addition, in order to comply with the stateless nature of HTTP, token authentication is often adopted. Jsonwebtoken allows our Node application to implement this authentication.
7.3 What is a JSON Web Token?
JSON Web Token is an open standard protocol that defines a compact and self-contained way to securely transfer information between parties as JSON objects.
It has the following advantages:
- It applies to distributed single sign-on (SSO) scenarios.
- Cross-domain authentication solutions can be used.
- JWT implements an automatic token refresh scheme (to be certified).
const jwt = require('jsonwebtoken'); Obj Specifies the body to be signed. The parameter must be an Object, Buffer, or string. * signedText The key is a string or buffer containing the HMAC algorithm key or PEM encoded private key of RSA and ECDSA. * options signature Settings, such as expiration date const token = jwt.sign(obj, signedText, options); * /Copy the code
The options parameter has the following values:
Algorithm: encryption algorithm (default: HS256) expiresIn: a string representing or describing the time span zeit/ms in seconds. For example, 60, "2 days", "10h", and "7D", meaning: Expiration time notBefore: A string of seconds indicating or describing the time span zeit/ms. For example, 60, "2days", "10h", "7D" Audience: audience Issuer: issuer jWtid: JWT ID Subject: subject, noTimestamp headerCopy the code
Nodejs implements github code for JWT (github.com/auth0/node-…)
Jsonwebtoken = jsonWebToken = jsonWebToken = jsonWebToken = jsonWebToken = jsonWebToken
// generate a token const JWT = require(' jsonwebToken '); const secret = 'abcdef'; let token = jwt.sign({ name: 'laney' }, secret, (err, token) => { console.log(token); });Copy the code
Then we go to the directory in the project, execute node index.js, and see the command line will print the token, as follows:
Of course, we can also set the token expiration time, for example, set the token expiration time to 1 hour, as follows:
// generate a token const JWT = require(' jsonwebToken '); const secret = 'abcdef'; Let token = jwt.sign({name: 'kongzhi', exp: Math.floor(Date.now() / 1000) + (60 * 60) }, secret, (err, token) => { console.log(token); });Copy the code
Date.now() : in milliseconds Return value: Returns the number of milliseconds since 00:00:00 UTC, January 1, 1970.
Note: exp(expiration time) can be set only when payload is an object literal. If the payload is not a buffer or string, it is cast to the used string json.stringify ().
var d = Date(Date.now()); // Convert the number of milliseconds in the date string a = d.tostring (); Document. write(" The current date is: "+ a);Copy the code
Jwt. verify(token, secretOrPrivateKey, [options, callback])
This method is to verify the validity of the token
Grammar:
Jwt. verify(client_token, signedText, function(err, decode) { if (err) return; console.log(decode); });Copy the code
For example, if the generated token is set to 1 hour, the generated token is:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoibGFuZXkiLCJpYXQiOjE1OTY0NDczNzB
9.pmTWC2jNjyGuKQ2Nk_DEzXebf8bIhCGPkQGEb94obI4
Copy the code
Verify jwt.verify
const jwt = require('jsonwebtoken');
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoibGFuZXkiLCJpYXQiOjE1OTY0NDczNzB
9.pmTWC2jNjyGuKQ2Nk_DEzXebf8bIhCGPkQGEb94obI4';
const secret = 'abcdef';
jwt.verify(token, secret, (error, decoded) => {
if (error) {
console.log(error.message);
}
console.log(decoded);
});
Copy the code
7.5. Serve – static
Node.js is a server for dynamic pages, but it can also be used as a server for static Html pages, such as Nginx Apache. There are no configuration optimizations for Nginx. The steps are as follows:
-
Installation: YARN add serve-static connect
-
Create a file named server.js in the current bin directory with the following contents
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);
Copy the code
- Run NodeJS
node server.js
Note that under the bin directory to create the index. The HTML and other static resources such as images, can through the browser to access your files: http://localhost:8080/index.html
configuration
Var connect = require('connect'); Var bodyParser = require('body-parser'); Var cookieParser = require('cookie-parser'); Var app = connect().use(bodyParser.json()) // json parser. Use (bodyParser.urlencoded({extended: True}). Use (cookieParser()) adds cross-domain processing. Use (function (req, res, SetHeader (' access-Control-allow-origin ', '*'); // Website you wish to allow to connect res.setheader (' access-Control-allow-origin ', '*'); Request methods you wish to allow res.setHeader(' access-control-allow-methods ', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader(' access-control-allow-headers ', '*'); WriteHead (200, {" content-type ": "text/plain; charset=utf-8"}); / / utf-8 code next (); // Next method is a recursive call}) add a simple interface. Use ('/info', function(req, res, Next) {//response Responds to request // Middleware console.log(req.method + "+ req.url); // console.log(req.body); // console.log(req.originalUrl, req.url); // Cookies that have not been signed console.dir('Cookies: ', req.cookies) // Cookies that have been signed console.log('Signed Cookies: ', req.signedCookies) var data={ "code": "200", "MSG" : "success", "result" : [{" id ": 1," name ":" Sonia ", "content" : "advertising 1"}, {" id ": 2," name ": "Ben", "content" : "advertising 2"}, {" id ": 3," name ":" lili ", "content" : "advertising 3}]} res. The end (JSON. Stringify (data)); next(); }); app.listen(3000);Copy the code
run
Depend on the input node server – run after installation is complete. The js interface access through http://localhost:3000/info
How to view the accepted parameters
A POST request
Nodejs hot loading
Supervisor sudo NPM install -g supervisor app.js
Hotnode sudo NPM -g install hotcode hotnode app.js
Mode 3: yarn Global add nodemon nodemon app.js
Start a local server using http-server
Download and install
npm install http-server -g
Enable the HTTP-server service
Enter http-server-c-1 (⚠️ if you only enter http-server, the page will not be updated synchronously after the code is updated)
Example Disable the HTTP-server service
Press ctrl-C to show the terminal ^ chttp-server stopped. The service is successfully shut down.
I. Formidable should handle files or pictures uploaded by POST
Form. The HTML file
< form action = "http://192.168.155.1:3000/dopost" method = "POST" enctype = "multipart/form - data" > < p > < input type = "file" Name = "uploadImg" > < / p > < p > < input type = "submit" value = "submit" > < / p > < / form >Copy the code
If file or image uploading is involved during form submission, you must set the form header, that is, add encType =”multipart/form-data” to the form label. Otherwise, uploading the file or image fails. Where the name attribute must be assigned.
Download and guide the package
NPM install formidable; const formidable = require(‘formidable’); To package.
To properly process the uploaded file and receive its contents, set the encType attribute of the form to multipart/form-data. Formidable is one of several modules in the Node community that can accomplish this task. Simple use as follows:
const formidable = require('formidable'); const app= require('connect')(); app .use(function(req, res) { if (req.method == 'POST') { const form = new formidable.IncomingForm(); // Upload path form.uploadDir = __dirname + '/public'; form.parse(req, function(err, fields, files) { res.end('upload complete! '); }); } }) .listen(3000);Copy the code
The usual code snippet for uploading an image using formidable is:
const formidable = require('formidable'); var connect = require('connect'); var app = connect(); app.use('/upload/img',function(req, res, next){ var form = new formidable.IncomingForm(); form.encoding='utf-8'; form.uploadDir = path.join(__dirname,'./static'); form.keepExtensions=true; form.parse(req,function(err,fields,files){ console.log(files) if (err){ return; }; var size=parseInt(files.uploadImg.size); If (size>1024*1024){res.send(" picture too big!" ) fs.unlink(files.uploadImg.path); return; }; res.end('upload success'); next(); }); }) .listen(3000);Copy the code