NodeJs-http module

1. Concept

HTTP (hypertext transport protocol) protocol; called Hypertext Transfer Protocol in Chinese,
is an application layer communication protocol based on TCP/IP.
This protocol specifies in detail the rules for mutual communication between the browser and the World Wide Web server.
The agreement mainly stipulates two aspects:

  • Client: used to send data to the server, which can be called a request message
  • Server: Returns data to the client, which can be called a response message

2. Composition of request message

  • request line
  • Request header
  • blank line
  • Request body

3. Composition of response message

  • response line

    HTTP/1.1 200 ok
    and some status codes, reference: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status

  • response header

    Cache-Control:缓存控制 private 私有的,只允许客户端缓存数据
    Connection 链接设置
    Content-Type:text/html;charset=utf-8 设置响应体的数据类型以及字符集,响应体为html,字符集
    utf-8
    Content-Length:响应体的长度,单位为字节
    
  • blank line

  • response body

  • The types of response body content are very flexible. Common types include HTML, CSS, JS, images, and JSON.

4. Create http service

Create HTTP service using nodejs

4.1 Operation steps

//1. 导入 http 模块
const http = require('http');
//2. 创建服务对象 create 创建 server 服务
// request 意为请求. 是对请求报文的封装对象, 通过 request 对象可以获得请求报文的数据
// response 意为响应. 是对响应报文的封装对象, 通过 response 对象可以设置响应报文
const server = http.createServer((request, response) => {
    
    
	//解决中文乱码
	response.setHeader("Content-Type","text/html;charset=utf-8")
	response.end('Hello HTTP server');
});
//3. 监听端口, 启动服务
server.listen(9000, () => {
    
    
	console.log('服务已经启动, 端口 9000 监听中...');
});

Execution timing of the callback function in http.createServer: When an HTTP request is received, it will be executed

4.2 Precautions

  1. Command line ctrl + c to stop the service

  2. After the service is started, the updated code must be restarted to take effect.

  3. Solution to Chinese garbled response content

    response.setHeader('content-type','text/html;charset=utf-8');
    
  4. Port number is occupied

    Error: listen EADDRINUSE: address already in use :::9000
    

    1) Close the service currently running on the listening port (used more)
    2) Modify other port numbers

  5. The default port of HTTP protocol is 80. The default port of the HTTPS protocol is 443, and the commonly used ports for HTTP service development are 3000, 8080
    , 8090, and 9000.

5. Obtain HTTP request message

To obtain the requested data, you need to pass the request object

meaning grammar
Request method request.method
Request version request.httpVersion
Request path request.url
URL path require(‘url’).parse(request.url).pathname
URL query string require(‘url’).parse(request.url, true).query
Request header request.headers
Request body request.on(‘data’, function(chunk){})
Request method request.method request.on(‘end’, function(){});

Precautions:

  1. request.url 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 converts the attribute names into "lowercase"
  3. About the path: If you only fill in the IP address or domain name information when accessing the website, the requested path is "/"
  4. About favicon.ico: This request is a request automatically sent by the browser

5.1 Get the request message

//1. 导入http模块
const http = require('http');
//2.创建服务对象 create 创建 server 服务
const server = http.createServer((request,response)=>{
    
    
    //1.获取请求方法
    console.log(request.method);
    //2.获取http版本
    console.log(request.httpVersion);
    //3.获取请求路径
    console.log(request.url);
    //4.获取请求头
    console.log(request.headers);
    // 响应内容中文乱码的解决办法
    response.setHeader('content-type','text/html;charset=utf-8');
    response.end("你好啊");
})
//3.监听端口,启动服务
server.listen(8080,()=>{
    
    
    console.log("服务已经启动");
})

5.2 Extract path and query string

Method 1: Introduce the url module

//1. 导入http模块
const http = require('http');
//导入url模块
const url = require('url');
//2.创建服务对象 create 创建 server 服务
const server = http.createServer((request,response)=>{
    
    
    //解析request.url
    // console.log(request.url);
    let res = url.parse(request.url,true);
    //路径
    console.log(res.pathname);
    //查询字符串
    console.log(res.query.wd);

    response.end('url')

})
//3.监听端口,启动服务
server.listen(9000,()=>{
    
    
    console.log("服务已经启动");
})

Method 2: Instantiate the URL object

//1. 导入http模块
const http = require('http');
//2.创建服务对象 create 创建 server 服务
const server = http.createServer((request,response)=>{
    
    
    //实例化url对象
    let url = new URL(request.url,'http://127.0.0.1:9000');
    //路径
    console.log(url.pathname);
    //查询字符串
    console.log(url.searchParams.get('wd'));

    response.end('url new ')

})
//3.监听端口,启动服务
server.listen(9000,()=>{
    
    
    console.log("服务已经启动");
})

6. Set HTTP response message

effect grammar
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’) or response.end(‘xxx’)
write 和 end 的两种使用情况:
//1. write 和 end 的结合使用 响应体相对分散
response.write('xx');
response.write('xx');
response.write('xx');
response.end(); //每一个请求,在处理的时候必须要执行 end 方法的
//2. 单独使用 end 方法 响应体相对集中
response.end('xxx');

Sample code:


//1.导入http模块
const http = require('http');
//2.创建对象
const server = http.createServer((request,response)=>{
    
    
    //设置响应状态码
    response.statusCode = 203;
    //响应状态描述
    response.statusMessage = "hello world"
    //设置响应头
    response.setHeader('content-type','text/html;charset=utf-8');
    response.setHeader('test',['a','b','c']);
    //设置响应体 ,write可以写多次,end只能出现一次
    response.write("write写入");
    response.write("write写入");
    response.write("write写入");

    response.end('end写入')

})
//3.监听端口,开启服务
server.listen(9000,()=>{
    
    
    console.log("服务已启动")
})

7. MIME setting resource type

//1.导入http模块
const http = require('http');
//引入fs
const fs = require('fs');
//引入path模块
const path = require('path');
//mime类型数组
let mime = {
    
    
    html: 'text/html',
    css: 'text/css',
    js: 'text/javascript',
    png: 'image/png',
    jpg: 'image/jpeg',
    gif: 'image/gif',
    mp4: 'video/mp4',
    mp3: 'audio/mpeg',
    json: 'application/json'
}
//2.创建对象
const server = http.createServer((request,response)=>{
    
    
    let {
    
    pathname} = new URL(request.url,'http://127.0.0.1:9000')
    //拼接路径
    let filepath = __dirname + pathname;
    //异步fs读取
    fs.readFile(filepath,(err,data)=>{
    
    
        if(err){
    
    
            response.end('响应失败');
            return;
        }
        //获取文件后缀
        let ext = path.extname(filepath).slice(1);
        //获取mime类型
        let type = mime[ext];
        type?response.setHeader("content-type",type+';charset=utf-8'):
            response.setHeader("content-type","application/octet-stream");
        response.end(data);
    })
})
//3.监听端口,开启服务
server.listen(9000,()=>{
    
    
    console.log("服务已启动")
})

Guess you like

Origin blog.csdn.net/lx00000025/article/details/132595955
Recommended