web server
When an application (client) needs a resource, it can obtain the resource from a server through Http request; The server that provides resources is a Web server;
First experience
// Introduce http module const http = require('http') // Create a web server const server = http.createServer((req, res) => { res.end('Hello Http') }) // Turn on the server and listen on the port server.listen(8000, 'localhost' ,() => { console.log('The server started successfully'); })
request
- req.url: the URL of this request. The server needs to process it differently according to different URLs;
- req.method: the request method of this request, such as the parameters passed in and processing methods of GET and POST requests are different;
- req.headers: the headers of this request will also carry some information, such as client information, format of received data, supported coding format, etc;
req.url
Sending requests using postman
url transfer data: localhost: 8000 / users? username=htf&password=123456
Basic usage
Return different contents according to different request paths
const http = require('http') // Create a web server const server = http.createServer((req, res) => { if(req.url == '/login') { res.end('welcome back'); } else if(req.url == '/user') { res.end('Welcome to the user list'); } else { res.end('The page does not exist'); } }) // Turn on the server and listen on the port server.listen(8000, () => { console.log('The server started successfully'); })
url module
When sending a request, it can be parsed with the help of the url module
const http = require('http') const url = require('url') // Create a web server const server = http.createServer((req, res) => { const parseInfo = url.parse(req.url) console.log(parseInfo); res.end('Sent successfully') }) // Turn on the server and listen on the port server.listen(8000, () => { console.log('The server started successfully'); })
At this time, the console outputs the object after successful parsing
Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?username=htf&password=123456', query: 'username=htf&password=123456', pathname: '/users', path: '/users?username=htf&password=123456', href: '/users?username=htf&password=123456' }
We can get query and pathname
const http = require('http') const url = require('url') // Create a web server const server = http.createServer((req, res) => { const { pathname, query } = url.parse(req.url) console.log(pathname, query); res.end('Sent successfully') }) // Turn on the server and listen on the port server.listen(8000, () => { console.log('The server started successfully'); })
Output result: / users username = HTF & password = 123456
The first mock exam can be done by borrowing another module to analyze query.
querystring
At this point, the console output (htf 123456) successfully parses the query
const http = require('http') const url = require('url') const qs = require('querystring') // Create a web server const server = http.createServer((req, res) => { const { pathname, query } = url.parse(req.url) const queryObj = qs.parse(query) console.log(queryObj.username); console.log(queryObj.password); res.end('Sent successfully') }) // Turn on the server and listen on the port server.listen(8000, () => { console.log('The server started successfully'); })
methods
{
"name": "htf",
"password": "123456"
}
The json data in the above body sends the request through post
const http = require("http"); const url = require("url"); const qs = require("querystring"); // Create a web server const server = http.createServer((req, res) => { const { pathname } = url.parse(req.url); // Can judge the request mode if (req.method === "POST") { if (pathname == "/login") { // Get the data in the body // Specifies the encoding method, otherwise binary is returned req.setEncoding("utf-8"); req.on("data", (data) => { // Because the json data sent is parsed in this way const { name, password } = JSON.parse(data); console.log(name, password); // htf 123456 }); } else { res.end("The page does not exist"); console.log("Acceptance failed"); } } }); // Turn on the server and listen on the port server.listen(8000, () => { console.log("The server started successfully"); });
In Restful specification (design style), we should add, delete, modify and query data through different request methods
- GET: query data;
- POST: new data;
- PATCH: update data;
- DELETE: DELETE data;
headers
The header of the request object also contains a lot of information. The client will pass some information by default:
{ 'content-type': 'application/json', 'user-agent': 'PostmanRuntime/7.28.1', accept: '*/*', 'postman-token': 'bf377318-75ca-4a27-b524-6ffcfa9dddad', host: 'localhost:8000', 'accept-encoding': 'gzip, deflate, br', connection: 'keep-alive', 'content-length': '50' }
Content type is the type of data carried in this request
- application/json represents a json type;
- text/plain indicates text type;
- The application/xml representation is of xml type;
- Multipart / form data means upload file;
User agent: client related information;
Accept: tells the server that the client can accept the format type of the file;
Accept encoding: tell the server that the file compression format supported by the client, such as js files, can be gzip encoded, corresponding to gz documents;
Content length: the size and length of the file
connection: 'keep-alive'
- http is based on TCP protocol, but it is usually interrupted immediately after a request and response;
- In http1 0, if you want to stay connected:
- The browser needs to add connection: keep alive in the request header;
- The server needs to add connection: keey alive in the response header;
- When the client puts the request again, it will use the same connection and directly interrupt the connection on one side;
- In http1 1, all connections are connection: keep alive by default;
- Different Web servers have different keep alive times;
- Node defaults to 5s
response
Status code
Http Status Code is a digital code used to indicate the status of Http response
Status code | State description | explain |
---|---|---|
200 | OK | Client request succeeded |
400 | Bad Request | Because the client request has syntax error, it cannot be understood by the server |
401 | Unauthorized | The request is unauthorized. This status code must be used with the WWW authenticate header field |
403 | Forbidden | The server received the request but refused service. The server usually gives the reason why the service is not provided in the response body |
404 | Not Found | The requested resource does not exist. For example, enter the wrong URL |
500 | internal Serve Error | An unexpected error occurred on the server that prevented the client from completing the request |
503 | Service Unavailable | The server is currently unable to process the client's request. After a period of time, the server may return to normal |
Set status code
const http = require("http"); const url = require("url"); const qs = require("querystring"); // Create a web server const server = http.createServer((req, res) => { // Set status code // Method 1: directly assign values to attributes // res.statusCode = 404 // Method 2: set with head res.writeHead(404) // Response results res.end('Hello Http') }); // Turn on the server and listen on the port server.listen(8000, () => { console.log("The server started successfully"); });