Node.js network programming to realize the creation of HTTP, GET and POST

Posted by lhcpr on Sat, 25 Dec 2021 05:11:17 +0100

HTTP server and client (important)

HTTP Foundation

HTTP protocol: hypertext transmission control protocol, a general, stateless and data independent protocol (working at the application layer)

The process of interaction between server and client:

  1. Establish TCP connection between client and server (HTTP protocol is implemented based on TCP protocol)
  2. The client sends a request to the server
  3. The server returns response information to the client
  4. Close HTTP connection

Message:

The data block transmitted in the process of HTTP request and response is called message, including the data to be transmitted and some additional information, and shall comply with the specified format


Request message:

  • Request Method: Request Method

    • GET request data
    • POST send data
  • Request address: Request URL

Response message:

  • HTTP status code:
    • 200 request successful
    • 404 the requested resource was not found
    • 500 server side error
    • 400 client request has syntax error
  • Content type:
    • text/html
    • text/css
    • application/javascript
    • image/jpeg
    • application/json

http module

HTTP module: used to realize HTTP communication

Import the module:

const http = require('http');

1,http.Server class:

http. The server class provides the basic framework for implementing an HTTP server

Implemented events:

eventdescribe
requestThis event will be triggered when there is a request. Two parameters, request and response, are provided: http Incomingmessage object and HTTP Serverresponse object, which represents the information of request and response
connectThis event is triggered when a client requests the CONNECT method of HTTP
connectionThis event is triggered when TCP establishes a connection. The supplied parameter socket usually represents net Socket object
closeThis event is triggered when the server shuts down
clientErrorIf the client connection triggers an error event, it will be forwarded here

Methods provided:

  • server.listen() is used to start the HTTP server to listen for connections
  • server.close() is used to stop the server from accepting new connections

Main functions:

  • Establish a network listener based on TCP connection
  • Listen for its own request event

http.createServer() method:

  • Syntax format: http createServer([options][, requestlistener])
  • To start the HTTP server, you need to use HTTP The createserver () method creates an HTTP Server Object

2,http.IncomingMessage class - incoming information:

http. The incomingmessage object (an instance of this class) is created by http.Server or http.ClientRequest

Implemented events:

eventdescribe
abortedTriggered when the request is aborted
closeIndicates that the underlying connection is closed

Properties:

3,http.ServerResponse class - response:

Specify the response to send to the client

Implemented events:

eventdescribe
closeCall response End () method, or it can refresh the previously terminated underlying connection
finishThis event is triggered after the response is sent

Additional methods for response headers:

  • response.setHeader(name, value): set a specific response header
  • getHeader(name): get a response header that has been set in the response
  • removeHeader(name): removes a response header that has been set in the response
  • response. Add trainers (headers): add the HTTP tail response header to the response
  • response.writeHead(statusCode,[reasonPhrase],[headers]): write a response header to the request

Method for responders:

  • response.write(data,[encoding]): send the response body
  • response.writeContinue(): sends an HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent
  • response.end([data][,encoding][,callback]): ends the response and indicates to the server that all response headers and response bodies have been sent.

Properties:

  • response.statusCode: the status code that will be sent to the client when the response header is refreshed
  • response.statusMessage: the status message that will be sent to the client when the response header is refreshed

4,http.ClientRequest class:

http. The clientrequest class provides the basic framework for implementing HTTP clients

Via http The request () method creates and returns an HTTP Clientrequest object, as an HTTP client, starts, monitors and processes the response from the server

Implemented events:

eventdescribe
abortTriggered when the request is aborted by the client
connectThis event is triggered each time the server responds to a request using the CONNECT method
continueTriggered when the server sends a "100 Continue" HTTP response
responseTriggered when a response to this request is received. This event is triggered only once
socketTriggered after the Socket is assigned to this request
timeoutTriggered when the underlying Socket expires due to inactivity.

Method for request header:

  • request.setHeader(name, value): set a specific request header
  • request.getHeader(name): read a request header in the request
  • request.flushHeaders(): refresh request headers

Method for request body:

  • request.write(chunk[, encoding][, callback]): sends a data block of the request body
  • request.end([data[, encoding]][, callback]): complete the sending request
  • request.abort(): terminates the current request
  • request.setTimeout(timeout,[callback]): sets the Socket timeout for requests.

http.request() method:

  • Syntax format:
    • http.request(options[, callback])
    • http.request(url[, options][,callback])
  • To build an HTTP client, you need to use HTTP The request () method creates a ClientRequest object

Create HTTP server and client

Create HTTP server:

//Import http module
const http=require('http');
//Create http server parameter req: request object res: response object
//req: get client request data res: send response data to client
const server=http.createServer((req, res) => {
    console.log('Client URL: '+req.url);
    //Set the response header information parameter status code 200: indicates that the request response is successful. Content type: the format and character set (encoding format) of the response information
    res.writeHead(200,{'content-type':'text/html;charset=utf-8'});
    res.write('<h2>Hello World!</h2>');
    res.end();
});
//Bind port and start listening
server.listen(8080,()=>{
    console.log('The server listens on port 8080');
});

Create HTTP client:

//Import http module
const http=require('http');
//Import querystring module
const queryString=require('querystring');
//Create request data: convert the request data into JSON format through the stringify method of the queryString module
const postData=queryString.stringify({'msg':'Hello, I'm http client'});
//Create the configuration information of the request: server address, port, request resource address, request method, request header information
const options={
    hostname:'127.0.0.1',
    port:8080,
    path:'/upload',
    method:'post',
    headers:{
        'Content-Type':'application/x-www-form-urlencoded;charset=utf-8',
        'Content-Length':Buffer.byteLength(postData)
    }
}
//Send request to server: create request object
const req=http.request(options,(res) => {
    console.log(`Status code: ${res.statusCode}`);
    console.log(`Response header information: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data',chunk => {
        console.log(`Responder: ${chunk}`);
    });
    res.on('end',()=>{
        console.log('End of request');
    });
    res.on('error',(err => {
        console.log(err);
    }));
})
//Write the request data to the request body
req.write(postData);
//End of request
req.end();

GET request and POST request

Request parameters: when the client sends a request to the server, it sometimes needs to carry some customer information, which needs to be transmitted to the server in the form of request parameters.

GET request: include the request parameters in the url, that is, in the browser address bar, for example: http://localhost:8080/index?age=12

  • The request parameters are saved in the browser's history
  • Request data can only be encoded by URL
  • Parameter data types are limited and can only receive ASCII characters
  • Unsafe and unsuitable for transmitting sensitive information

Parameter acquisition requires the help of the system module url, which is used to process url addresses, and its parse() method is often used to convert them into objects

Request using GET method:

  • Browser address bar
  • href attribute of link tag
  • src attribute of script tag
  • src attribute of img tag
  • Form submission

Create server by GET:

//Import http url module
const http=require('http');
const url=require('url');
//Create server
var server=http.createServer((req, res) => {
    //Decode the client url
    let reqURL=decodeURI(req.url);
    //Convert url string to url object
    reqURL=url.parse(reqURL); //The intercepted content is not easy to distinguish
    console.log(reqURL);
    res.end('Submitted successfully!');
});
//Bind and listen port
server.listen(8080);

Create client by GET:

//Import http module
const http=require('http');
//Set the requested configuration information
const options={
    hostname:'127.0.0.1',
    port:8080,
    path:encodeURI('/index.html?age=12&stats=open')
}
//Create a get request object and send a get request to the server
http.get(options,res => {
    res.setEncoding('utf8');
    res.on('data',chunk => {
        console.log('Response information:'+chunk.toString());
    });
}).on('error',err => {
    console.log(err.message);
})

POST request: include the request parameters in the request body

  • Request parameters are not saved in the browser's history
  • The request data supports multiple encoding formats
  • There are no restrictions on the data types of parameters
  • More secure for delivering sensitive information

To obtain POST parameters, you need to use data event and end event, and use querystring system module to convert parameters to object format

Request by POST:

  • Form submission

Create server in POST mode:

const http=require('http');
const queryString=require('querystring');
//Create server object for post request
var server=http.createServer((req, res) => {
    //The data variable is used to receive the request data sent by the client to the server
    let data='';
    req.on('data',chunk=>{
        //The parameter chunk stores the request data sent by the client to the server. The data is in binary format and is automatically converted into a string when connected to the variable data
        data=data+chunk;
    })
    //Bind the end event to the request object. This event will be triggered when the request ends
    req.on('end',()=>{
        //Decode the requested data
        data=decodeURI(data);
        console.log('Request data:'+data);
        //Convert request data to objects
        let dataObj=queryString.parse(data);
        console.log('Converted request data:',dataObj);
        console.log('full name:',dataObj.name);
        console.log('Identity:',dataObj.title);
        res.end('Submitted successfully!');
    });
});
server.listen(8080);

Create client in POST mode:

const http=require('http');
const queryString=require('querystring');
//Convert the data to be submitted to the server into a query string (JSON format data)
var postData=queryString.stringify({
    'name':'Zhang San',
    'title':'student'
});
//Create configuration information
var options={
    hostname:'127.0.0.1',
    port:8080,
    method:'post'
};
//Create post request object
//The object created with the request method is that the method in options is post
const req=http.request(options,res => {
    res.setEncoding('utf8');
    res.on('data',chunk => {
        console.log('Response data:'+chunk.toString());
    });
});
//Writes the requested data to the request object
req.write(postData);
//End request
req.end();

Topics: node.js socket http post get