HTTP module of Nodejs

Table of Contents

  • foreword
  • 1. Create an HTTP module
    • 1.1 Basic use
    • 1.2 Precautions
  • Second, view the message
    • 2.1 Browser view HTTP message
    • 2.2 Use request to get HTTP request message
      • 2.2.1 Get request line and request header
    • 2.2.2 Get the request path
      • 2.2.3 Get query string
  • 3. Exercises related to request messages
  • Fourth, set the response message
  • Five, HTTP response practice
  • Six, web resources
    • 6.1 Basic process of web page resource loading
    • 6.2 Realize the introduction of external resources into web pages
    • 6.3 Static resources and dynamic resources
  • postscript

Foreword

To learn the content of this section, you need to have a certain understanding of the client sending requests, and you need to have a basic knowledge of nodejs.

If the knowledge is not well grasped, you can see the relevant content in my column:
Front-end and back-end interaction knowledge reserve
Nodejs

Without further ado, let’s start learning.

One, create HTTP module

1.1 Basic usage

HTTP is a built-in module of Nodejs. It can be used directly without npm download. The basic usage is as follows:

//Import httpmok
const http = require('http');

//Create service object
const server = http.createServer((request, response) => {<!-- -->
    response.end('Hello HTTP Server');//Set the response body and end the response
});

//Listen to the port and start the service
server.listen(9000, () => {<!-- -->
    //Service started successfully
    console.log('service started')
})

The above module is about request and response. The request encapsulates the relevant content of the request message, and we can see the request content sent by the client through the request; while the response encapsulates the relevant content of the response message.

Here you can refer to my article:
Network planning knowledge related to the front end

Continuing with the code just now, we first run it in the terminal:

Then open port 9000 of the local loopback address:

1.2 Notes

1. Command line ctrl + c to stop the service;

2. After the service is started, the update code must restart the service to take effect;

3. Response content garbled solution:

response.setHeader('content-type', 'text/html;charset=utf-8');

Second, check the message

There are two types of messages, which are divided into request messages and response messages. The content of this section is very critical, teaching readers how to obtain messages through browsers and writing codes.

2.1 Browser view HTTP message

Run the backend code, open the local loopback address, open the terminal with f12, and click ‘Network’:

Click to request:

On the right is related content.

But now we can’t see the request body, because most of the request body of the get request is empty. So we now write a post:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="http://127.0.0.1:9000" method="post">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" value="submit">
    </form>
</body>
</html>

After clicking post, there will be an additional ‘load’, which contains the formatted request body content.

You can also click “View Source Code” above to see the original request body content:

2.2 Use request to get HTTP request message

The previous section explained the view of the message. In fact, in actual operation, the acquisition of the request message is more important, because we need to obtain the content of the request initiated by the user, and then give the user the correct response result.

2.2.1 Get request line and request header

Get through the request object:

Meaning Syntax
Request method request.method
request path request.url
URL path request(‘url’).parse(request.url).pathname
URL query string request(‘url’). parse(request.url,true).query
request header request.headers
Request body request.on(‘end’, function(){})

A few notes:
1. The request can only obtain the path and query string, but cannot obtain the domain name and protocol content in the URL;

2. request.headers converts the request information into an object, and the attribute names are all lowercase;

3. Regarding the path, if you only fill in the IP address or domain name information when visiting the website, the requested path is ‘/’;

4. About favicon.ico: This request is a request sent automatically by the browser.

2.2.2 Get request path

Here is a built-in module: url.

The first is also the normal import process:

//import url module
const url = require('url')

Then there is routing and monitoring:

const server = http.createServer((request, response) => {<!-- -->
    // Parse the content of request.url
    let res = url.parse(request.url);//parse is a method of url itself, the word means parsing
    console. log(res)
    response.end('url')
})

server.listen(9000, () => {<!-- -->
    console.log('service started')
})

After we execute it with a form input, the URL will be printed:

Among them, pathname is the address we need.

2.2.3 Get query string

On the basis of just now, add a ‘true’ after parse:

Run it again, the following will get some objects:

query string:

Three, exercises related to request messages

Requirements: Build an HTTP service according to the following requirements:

request type request address response body result
get /login login page
get /reg Registration page

code:

const http = require('http');

const server = http.createServer((request, response) => {<!-- -->
    //Judge the request method, url path
    let {<!-- -->method} = request
    let {<!-- -->pathname} = new URL(request.url, 'http://127.0.0.1')
    console. log(method)
    console.log(pathname)
    response.setHeader('content-type', 'text/html;charset=utf-8');
    if(method == "GET" & amp; & amp; pathname === '/login') {<!-- -->
        response.end('login page')
    }
    if(method == "GET" & amp; & amp; pathname === '/reg') {<!-- -->
        response.end('registration page')
    } else {<!-- -->
        response.end('404 Not Found')
    }
})

server.listen(9000, () => {<!-- -->
    console.log('service has started')
})

Fourth, set the response message

In the previous content, we have learned how to obtain the request message. After obtaining the request message, we need to give feedback to the user, so this section is to tell readers how to set the response message.

Action Syntax
Set response status code response.statusCode
Set response status description response.statusMessage (very rarely used)
Set response header information response.setHeader(‘header name’, ‘header value’)
Set response body response.write(‘xx’) response.end(‘xxx’)

The request must have end. Yes and only once.

5, HTTP response practice

Build an HTTP service and respond to a table with 4 rows and 4 columns:

const http = require('http')

const server = http.createServer((request, response) => {<!-- -->
    response.setHeader('content-type', 'text/html;charset=utf-8')
    response. end(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            td {
                padding: 20px 40px;
            }
            table, td {
                border-collapse: collapse;
            }
        </style>
    </head>
    <body>
        <table border="1">
            <tr><td><td/><td><td/></tr>
            <tr><td><td/><td><td/></tr>
            <tr><td><td/><td><td/></tr>
            <tr><td><td/><td><td/></tr>
        </table>
    </body>
    </html>
    `)
})

server.listen(9000, () => {<!-- -->
    console.log('service has started')
})

In these codes, html, css, and js are actually written in js. very troublesome. How to solve this problem?

Optimized version: Take out the content written in the three-piece suit, and put it directly into the end.

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

const server = http.createServer((request, response) => {<!-- -->
    response.setHeader('content-type', 'text/html;charset=utf-8')
    let html = fs.readFileSync(__dirname + './returned form.html')
    response.end(html)
})

server.listen(9000, () => {<!-- -->
    console.log('service has started')
})

Six, web resources

6.1 Basic process of web page resource loading

Not all at once, one load, but a gradual process.

In general, several loads are sent out in parallel, waiting for the results to come back.

6.2 Realize the introduction of external resources into web pages

In the case of the fifth section, we read the file through fs, and after reading the file, end it out.

Now let’s try to make the content in index.html only html, and import styles and js in index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <div class="box">
        <h3>This is a case of citing external resources</h3>
        <h3>I'm not happy at all</h3>
        <h3>I feel like my happiness is being pulled away</h3>
        <button class="btn">Click the button, make me happy again</button>
    </div>
    <script src="./index.js"></script>
</body>
</html>

If you directly read and end like the fifth section, what will happen is: no style, no js.

The style is there:

Why doesn’t it take effect?

Click on the css request to see: Even if it is a css request, it is still html after clicking on it:

The same is true for js:

How to solve it: Adjust the code of the callback function.

According to the content, distinguish the request, that is, return the content according to the request header.

const fs = require('fs')
const http = require('http')

const server = http.createServer((request, response) => {<!-- -->
    //Get request path
    let {<!-- -->pathname} = new URL(request.url, 'http://127.0.0.1')
    if(pathname === '/') {<!-- -->
        const neirong = fs.readFileSync(__dirname + '/index.html')
        response.end(neirong)
    } else if(pathname === '/index.css') {<!-- -->
        const neirong = fs.readFileSync(__dirname + '/index.css')
        response.end(neirong)
    } else if(pathname === '/index.js') {<!-- -->
        const neirong = fs.readFileSync(__dirname + '/index.js')
        response.end(neirong)
    } else {<!-- -->
        response.statusCode = 404;
        response.end('404 not found')
    }

})

server.listen('9000', () => {<!-- -->
    console.log('server started')
})

Finally, there will be a normal result:

(Please ignore my emo, nodejs is a real emo after reading it all afternoon)

6.3 Static resources and dynamic resources

Static resources: resources whose content does not change for a long time, such as pictures, videos, css files, js files, html files, font files, etc.;

Dynamic resources: Resources whose content is updated frequently, such as Baidu homepage, NetEase homepage, JD search list page, etc.

Postscript

The above is the relevant content of the htt module. Welcome to follow!