http 模块

VSCode 中,输入 node-http-server,自动创建一个 web 服务

//node-http-server
var http = require('http');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World');
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

运行这个程序,cd 到这个目录,然后 node + 文件名

浏览器打开这个地址,输出“ Hello World ”

手动创建一个 web 服务

//1,引入 http 模块
const http = require('http')
//2,创建服务器,回调函数表示接收到请求后做的事情
http.createServer(function(req,res){
    //发送HTTP头部,设置响应头
    res.writeHead(200,{"Content-Type":"text/html;charset=UTF-8"})
    //发送响应数据 "Hello World"
    res.end("Hello World") //end方法使Web服务器停止处理脚本并返回当前结果
}).listen("8888") //lisen方法绑定8888端口

解决中文乱码问题

const http = require('http')
http.createServer((req, res)=> {
    res.writeHead(200, { "Content-type": "text/html;charset='utf-8'" })
    res.write('hello world')
    res.write('<h3>你好,world</h3>') //有中文乱码问题
    res.end() //结束响应
}).listen("8888") //lisen方法绑定8888端口

 解决:

原文地址:https://www.cnblogs.com/shanlu0000/p/13140969.html