Http using node.js core module

http Nodejs module is the core module can be used directly without installation. Chinese document address is: http: //nodejs.cn/api/http.html

1. Basic use

First, create a new file in the project directory server.js, write the following in it:

// 引入核心模块
const http = require('http');
// 创建服务器
const sev = http.createServer();

// 为服务器绑定request事件 表示当用户的请求发送到的时候触发
// 回调函数的参数说明:
// 参数1:发起请求的客户端的信息
// 参数2:服务端处理响应的相关参数和方法
sev.on('request', function (request, response) {
    console.log(request);
    console.log(response);
    // 设置响应编码,防止乱码的出现
    response.setHeader('Content-Type', 'text/html;charset=utf-8');
    // 结束响应
    response.end('你好啊!');
});

// 设置服务器监听的端口
sev.listen('80', '127.0.0.1', function(){

});

Then run the command line:

node ./server.js

If there is no error, indicating that lacks the problem we write, this time we can access in your browser: http://127.0.0.1:80to see the effects.

Introduction 1. http.Server class

We previously used the code const s = http.createServer();to get the return value is a http.Serverclass, here's what some of the common properties and methods of the class.

http.serverHTTP is a server-based event, all requests are encapsulated into a separate incident, we only need a few lines of his writing the corresponding event you can achieve all the features of the HTTP server

1.1 common events

  1. requestEvent
    when a client request comes in, the event is triggered, two parameters requestand response, respectively, http.IncomingMessageand http.ServerResponseexamples of, respectively, information requests and responses.
  2. connectionEvent
    when the TCP connection is established, the event is triggered, providing a parameter socket, net.socket an instance of (the underlying protocol object)
  3. closeEvent
    when the server will be closed when the trigger
    of course he still has a lot of other events, the most commonly used is the requestevent, such as in front of us write:
const s = http.createServer();
s.on('request', function (request, response) {  
});

http.Server Chinese document: http: //nodejs.cn/api/http.html#http_class_http_server

Introduction 2. http.IncomingMessage class

http.IncomingMessageExamples of recording the HTTP request message, is transmitted to the client and the client side of some of the information service, the server acquires data typically transmitted from the front end here.

2.1 Common property

name meaning
complete The client request has been sent to complete
httpVersion (common) HTTP protocol version, usually 1.0 or 1.1
method (commonly used) The method of HTTP request, such as: GET, POST
url (common) Original request path
headers (common) HTTP request header
connection The current HTTP connection socket, is an example of net.Socket
socket Alias ​​connection properties
client Alias ​​client properties
console.log(request.url);
console.log(request.headers);
console.log(request.method);
console.log(request.httpVersion);

3. http.ServerResponse 类

http.ServerResponseThe examples are intended to response data from the server to the client.

3.1 Common properties and methods

  1. write(chunk[, encoding][, callback])
    A data transmission request block body, the method can be called multiple times to provide a continuous body in response to fragment

    response.write('我好帅啊!哈哈哈');
    response.write('我真滴帅!哈哈哈');
    
  2. end([data[, encoding]][, callback])
    This method signals to the server, indicating that all responses have been sent and the head body, this should be considered the message server has been completed. This must be called on each response response.end()method. The method may also send the binary data directly.

  3. setHeader(name, value)
    A header information set, if the response header already exists, the value is overwritten. To send the same name in response to a plurality of heads, the array of strings.

  4. ** statusCode** property
    setting response status code.response.statusCode = 404;

  5. writeHead(statusCode[, statusMessage][, headers])

    Setting response headers, usually in a higher position calls, response.setHeader()response headers and will set the response.writeHead()response header of the merger, and response.writeHead()the priority Chinese document addresses
    Chinese documents address: http: //nodejs.cn/api/http.html# http_class_http_serverresponse

4. Write a static page processing server

// 引入核心模块
const http = require('http');
const fs = require('fs');
const path = require('path');
// 创建服务器
const sev = http.createServer();
sev.on('request', function (request, response) {
    // 获取用户要请求的文件路径
    let filePath = __dirname+request.url;
    let ext = path.extname(filePath);
  	// 处理文件的响应数据类型
    if(ext == '.html'){
        response.setHeader('Content-Type', 'text/html;charset=utf-8');
    }else if(ext == '.css'){
        response.setHeader('Content-Type', 'text/css;charset=utf-8');
    }

    // 读取文件
    fs.readFile(filePath, function (err, data) {
        if (!err) {
            // 结束响应并将数据响应给客服端
            response.end(data);
        }else{
            response.end('您访问的文件不存在');
        }
    })
});

// 设置服务器监听的端口
sev.listen('80', '127.0.0.1', function () {
          console.log('服务器已启动');
});

5. http post request processing module

//首先引入各个模块
const http = require('http');
//文件操作模块
const fs = require('fs');
//
const path = require('path');
//
const url = require('url');
// 创建服务器
const sev = http.createServer();
sev.on('request', function (request, response) {
    let filePath = __dirname + request.url;
    if (request.method == 'POST') {
        var us = url.parse(request.url);
        if(us.path = '/123'){
            // 当请求的数据到达的时候,在这里接收数据
            request.on('data', function(chunk){
                console.log(chunk.toString());
              
              // 上传文件的话,可以根据request.headers['content-type']的值进行判断来决定后续如何处理
            })
        }
        response.end();

    } else {
      	// 处理post以外的请求
        let ext = path.extname(filePath);
        if (ext == '.html') {
            response.setHeader('Content-Type', 'text/html;charset=utf-8');
        } else if (ext == '.css') {
            response.setHeader('Content-Type', 'text/css;charset=utf-8');
        }

        // 读取文件
        fs.readFile(filePath, function (err, data) {
            if (!err) {
                // 结束响应并将数据响应给客服端
                response.end(data);
            } else {
                response.setHeader('Content-Type', 'text/html;charset=utf-8');
                response.end('您访问的文件不存在');
            }
        })
    }
});

// 设置服务器监听的端口
sev.listen('80', '127.0.0.1', function () {
    console.log("您的服务器已启动");
});
Published 22 original articles · won praise 0 · Views 1157

Guess you like

Origin blog.csdn.net/bigpatten/article/details/103622668