使用 nodeJS 搭建 HTTP 服务

//1. response.end([data[, encoding]][, callback])#
// 参数
// data <string> | <Buffer>
// encoding <string>
// callback <Function>
// 返回: <this>
// 此方法向服务器发出信号,表明已发送所有响应头和主体,该服务器应该视为此消息已完成。 必须在每个响应上调用此 response.end() 方法。

// 如果指定了 data,则相当于调用 response.write(data, encoding) 之后再调用 response.end(callback)。

// 如果指定了 callback,则当响应流完成时将调用它。

// 2.response.setHeader(name, value)#
// 参数
// name <string>
// value <any>
// 为隐式响应头设置单个响应头的值。 如果此响应头已存在于待发送的响应头中,则其值将被替换。 在这里可以使用字符串数组来发送具有相同名称的多个响应头。 非字符串值将被原样保存。 因此 response.getHeader() 可能返回非字符串值。 但是非字符串值将转换为字符串以进行网络传输。

// response.setHeader('Content-Type', 'text/html');

// 3.每次脚本修改后,都要重新在终端开启node服务,服务结束,ctrl+c


//使用 nodeJS 搭建 HTTP 服务
//1. 引入 http 模块
const http = require("http");

//2. 创建服务对象  
// request 请求   是对请求报文的封装的对象
// response 响应  是对响应报文封装的对象
const server = http.createServer(function (request, response) {
    //设置响应体
    // response.end("hello nodeJS server");
    // response.end(`<!DOCTYPE html>
    //     <html lang="en">
    //     <head>
    //         <meta charset="UTF-8">
    //         <meta name="viewport" content="width=device-width, initial-scale=1.0">
    //         <title>Document</title>
    //     </head>
    //     <body>
    //         <p>我和我的祖国</p>
    //     </body>
    //     </html>`);

    //设置响应头信息
    response.setHeader("content-type","text/html;charset=utf-8");
    response.end("我和我的祖国, 一刻也不能分开");
});

//3. 启动服务
// HTTP 服务的默认端口是 80
// HTTPS 服务的默认端口是 443
// 8000  端口号  计算机入口  65536 个端口. 建议使用 > 1024.  8080  8000  9000  3000
server.listen(8000, function () {
    console.log("服务已经启动");
});

//1. 修改了代码没有重启服务
//2. 访问的时候, URL 出错
//3. 把 fiddler 关闭
原文地址:https://www.cnblogs.com/fsg6/p/13081839.html