Node.js+postman to simulate HTTP server and client interaction

Node.js+postman to simulate HTTP server and client interaction

When an application (client) needs a certain resource, it can obtain the resource from a server through an HTTP request. The server that provides resources is the web server (created with node.js in this article), and postman is used to simulate the client to send requests to the server.

insert image description here

1. Node builds HTTP server

The http module is used in node to create an HTTP server . Whenever a new request is received, the request event will be called and provide two objects: a request req (http.IncomingMessage object) and a response res (http.ServerResponse object).

request provides the details of the request. It provides access to the request headers and request data. (Client–>Server)

response is used to construct data to be returned to the client (server–>client). Below is a simple HTTP web server example.

The following is an example of a simple HTTP server

//Import http module const http = require('http')

// Create an http server const server = http.createServer((req, res) => {
		//Set the statusCode property to 200 to indicate a successful response res.statusCode = 200
  		// res essentially inherits the stream.Writable class // After sending the response header and body to the client, tell the server that the message transmission is over res.end("hollow server")
        // Equivalent to res.writer("hollow server")+res.end()
    })
    // Listen to the server. When the server is ready, the listen callback function will be called // The console prints that the startup is successful server.listen('8089', 'localhost', () => {
    console.log("Startup successful")
})

At this point your local server is set up, you can go to the browser to open localhost:8089 to view

insert image description here

2. HTTP server processes get request

Postman is a commonly used interface testing tool that can send almost all types of HTTP requests. Postman is suitable for different operating systems, Postman Mac, Windows X32, Windows X64, Linux systems, and also supports postman browser extensions, postman chrome applications, etc.

Downloading is also very simple, you can click here to go directly to the official website to download 👉👉👉 Download Postman

1. Postman sends a get request

Create a new request in Postman , fill in the host address of the HTTP server we created above with node.js , as well as the username and password http://localhost:8089/login?username=ahua&password=123 in Enter request url, select GET as the request type, click Send, and Postman will send a get request to the server

insert image description here

2. Server analysis

The server receives the get request from the client (postman) and processes the data sent

const http = require('http')
    // Module for processing URLs const url = require('url')
    // Module that handles query const qs = require('querystring')
const server = new http.Server((req, res) => {
    // The request object encapsulates all the information passed by the client to our server // Parse the url const { pathname, query } = url.parse(req.url)
    if (pathname === '/login') {
        //console.log(query)
            // qs's parse method can process the query // Convert the string type to a js object username=ahua&password=123 --> {username: 'ahua',password: 123}
        //console.log(qs.parse(query))
        const { username, password } = qs.parse(query)
        console.log(username, password)
        res.end('request result')
    }
    console.log(req.url)
    //Print request type console.log(req.method)
    //Request header console.log(req.headers)
})
server.listen('8089', 'localhost', () => {
    console.log("serve started successfully")
})

The analysis result on the server side

insert image description here

3. HTTP server processes post request

1. Postman sends a post request

In the above get request, putting the username and password in the address bar may not be safe enough. To be more cautious in handling the account password, put them in the body and send them to the server using a json file.

The following figure shows the operation of postman putting username and password in json file and passing it to the server through bady

insert image description here

2. Server analysis

The server receives the post request from the client (postman) and processes the data sent. First, you should determine whether it is a post request, then get the data in the body, and then parse the data.

const http = require('http')
    // Module for processing URLs const url = require('url')
const server = new http.Server((req, res) => {
    // Get the pathname in the URL sent by the client
    const { pathname } = url.parse(req.url)
        // Determine whether it is login
    if (pathname === '/login') {
        // Determine whether the request sent by the client is a post request if (req.method === 'POST') {
            // Define the default encoding format for data sent from the client req.setEncoding('utf-8')
                // req.setEncoding('binary') binary defines binary encoding // Get the data in the body // The data in the body is written through the stream // When the data event is listened to, the input stream is obtained, that is, the relevant content in the body, and the result of this data can be returned req.on('data', (data) => {
                // JSON.parse() converts the string in the object into a js object // {"username":"阿花","passward":"123"} ---> {username: 'ahua',password: 123}
                const { username, password } = JSON.parse(data)
                console.log(username, passward)
            })
        }
    }

    res.end('request result')

})
server.listen('8089', 'localhost', () => {
    console.log("serve started successfully")
})

Server print request results

insert image description here

This completes a simple server interaction process.

This is the end of this article about node.js+postman to simulate HTTP server and client interaction. For more related node.js+postman server and client interaction content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the configuration of Express session and cookie module packages under the node.js platform
  • Practical application of angular2+node.js express packaging and deployment
  • How to install the latest version of Node.js on CentOS 8.2 server
  • Steps to create a WEBSERVER using NODE.JS
  • Detailed explanation of how to configure the local Vue project to request the local Node.js server
  • Node.js three steps to implement a server and Express package use

<<:  How to install JDK and Mysql on Ubuntu 18.04 Linux system

>>:  How to handle MySQL numeric type overflow

Recommend

Implementation of built-in modules and custom modules in Node.js

1. Commonjs Commonjs is a custom module in nodejs...

Detailed explanation of Mysql transaction isolation level read commit

View MySQL transaction isolation level mysql> ...

Detailed explanation of CSS margin collapsing

Previous This is a classic old question. Since a ...

Tutorial on using Docker Compose to build Confluence

This article uses the "Attribution 4.0 Inter...

Detailed tutorial on installing Python 3.6.6 from scratch on CentOS 7.5

ps: The environment is as the title Install possi...

JavaScript to implement drop-down list selection box

This article example shares the specific code of ...

How to get the real path of the current script in Linux

1. Get the real path of the current script: #!/bi...

Mysql example of splitting into multiple rows and columns by specific symbols

Some fault code tables use the following design p...

Summary of some HTML code writing style suggestions

Omit the protocol of the resource file It is reco...

9 Tips for MySQL Database Optimization

Table of contents 1. Choose the most appropriate ...

JavaScript function call classic example code

Table of contents JavaScript function call classi...

CentOS server security configuration strategy

Recently, the server has been frequently cracked ...

Tomcat uses Log4j to output catalina.out log

Tomcat's default log uses java.util.logging, ...

js canvas realizes rounded corners picture

This article shares the specific code of js canva...