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

Introduction to local components in Vue

In Vue, we can define (register) local components...

Introduction to the use of anchors (named anchors) in HTML web pages

The following information is compiled from the Int...

Practical operation of using any font in a web page with demonstration

I have done some research on "embedding non-...

Implementation of docker view container log command

Why should we read the log? For example, if the c...

Let's take a look at some powerful operators in JavaScript

Table of contents Preface 1. Null coalescing oper...

Use of Vue filters and custom instructions

Table of contents Filters 01.What is 02. How to d...

How to view the execution time of SQL statements in MySQL

Table of contents 1. Initial SQL Preparation 2. M...

Vue+Vant implements the top search bar

This article example shares the specific code of ...

Docker installs Elasticsearch7.6 cluster and sets password

Starting from Elasticsearch 6.8, free users are a...

XHTML Getting Started Tutorial: Commonly Used XHTML Tags

<br />Just like an article, our web pages sh...

Simple web design concept color matching

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

Correct use of Vue function anti-shake and throttling

Preface 1. Debounce: After a high-frequency event...

Implementation of Linux command line wildcards and escape characters

If we want to perform batch operations on a type ...

Practical solution for Prometheus container deployment

environment Hostname IP address Serve Prometheus ...