Usage and execution process of http module in node

Usage and execution process of http module in node

What is the role of http in node

The responsibility of the http module is to help you create and write servers

Execution Process

1. Load the http module

const http = require('http')

2. Use the http.createServer method to create a web server and return a server instance

const server = http.createServer()

3. Provide services for data

Send request Accept request Process request Return (send response)
Register the request event. When the client requests, the request event will be automatically triggered and the callback function with the second parameter will be executed.

server.on('request',function(){
    console.log('Received client request')
})

4. Bind the port number and start the server

server.listen(3000,()=> {
    console.log("The server started successfully and can be accessed through http://127.0.0.1:3000/")
})

5. node app.js started successfully

Open the browser and copy and paste http://127.0.0.1:3000/. You will find that the browser keeps spinning (a link has been established with the browser). At the same time, the terminal returns that it has received the client's request. If you close the terminal and press ctrl+c, the browser service will be terminated (the browser will not spin and the connection will be terminated).

Building a basic web server request

The code is as follows:

const http = require('http')

const server = http.createServer()
// The request event handler needs to receive two parameters // The request object // The request object can obtain some request information from the client, such as the request path // The response object // The response object can be used to send a response message to the client server.on('request', function(request, response) {
    console.log('Received the client's request', 'The request path is: '+request.url)
    // The response object has a method, write, which can be used to send response data to the client. // write can be used multiple times, but the last time you must use end to end the response, otherwise the client will keep waiting for response.write("hello")
    response.write("nodejs")
    response.end()
    //Tell the client that I have finished speaking and you can show it to the user //Since our server capabilities are very weak now, no matter what the request is, it can only respond with hello nodejs
    // How to request different paths and respond to different results})
server.listen(3000,()=> {
    console.log("The server started successfully and can be accessed through http://127.0.0.1:3000/")
})

The next step is to write a basic interface data to request

Determine the home page data displayed on different pages

insert image description here

a Page data …data that is different from the home page

const http = require("http")
const server = http.createServer()
server.on('request',function(req,res){
    res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
    console.log("Request received, request path is: "+req.url)
    // res.write("heel")
    // res.write("world")
    //res.end()
    // The above method is more troublesome // You can send a response when using end // Send different request results according to different request paths //1. Get the requested path // req.url gets the path after the port number // That is to say, all urls start with / //2. Determine the path and process the response const url = req.url
    if(url=="/"){
        const project = [
           {
            name:"Apple",
            price:"18",
           },
           {
            name:"Banana",
            price:"28",
           },
           {
            name:"Watermelon",
            price:"20",
           },
           {
            name:"xxx",
            price:"100",
           },
           {
            name:"aaa",
            price:"100",
           }
        ]
        // Response data can only be binary data or string // Response data cannot be: number object array Boolean value res.end(JSON.stringify(project))
    }else if(url=='/a'){
        const a = [
            {
             name:"Apple",
             price:"aa",
            },
            {
             name:"Banana",
             price:"ww",
            },
            {
             name:"Watermelon",
             price:"vv",
            },
            {
             name:"wjcx",
             price:"bb",
            },
            {
             name:"wdwa",
             price:"ww",
            }
         ]
         res.end(JSON.stringify(a))
    }
})
server.listen(3000,function(){
    console.log("Server started successfully, you can access it now! http://127.0.0.1:3000/")
})

This is the end of this article about the use of http module in node. For more relevant node http module 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:
  • Usage of Node.js http module
  • Node.js uses the http module to create a complete example of server and client
  • NodeJS http module usage example [Creating a web server/client]
  • Detailed explanation of the use of net and http in Nodejs core modules
  • Detailed explanation of the node.js http module example demonstration
  • Node.js advanced core module https introduction
  • Example of how to use the http module in nodejs to send get and post requests
  • A brief introduction to http module and url module in node.js

<<:  How to build LNMP environment on Ubuntu 20.04

>>:  Two ways to open and close the mysql service

Recommend

Simple web design concept color matching

(I) Basic concepts of web page color matching (1) ...

How to implement scheduled backup of MySQL database

1. Create a shell script vim backupdb.sh Create t...

How to delete folders, files, and decompress commands on Linux servers

1. Delete folders Example: rm -rf /usr/java The /...

How to use Docker to package and deploy images locally

First time using docker to package and deploy ima...

JavaScript to implement checkbox selection or cancellation

This article shares the specific code of JavaScri...

Research on the value of position attribute in CSS (summary)

The CSS position attribute specifies the element&...

CentOS6 upgrade glibc operation steps

Table of contents background Compile glibc 2.14 M...

Vertical and horizontal splitting of MySQL tables

Vertical Split Vertical splitting refers to the s...

Implementing a web player with JavaScript

Today I will share with you how to write a player...

MySql 8.0.11 installation and configuration tutorial

Official website address: https://dev.mysql.com/d...

How to implement variable expression selector in Vue

Table of contents Defining the HTML structure Inp...