使用Node.js搭建一个简易Web服务器

3,887 阅读1分钟

index.js内容:

// 1、加载模块
const http = require('http');
// 2、创建http
var server = http.createServer(); // 创建一个web容器 静态服务器
// 3、监听请求事件
server.on('request', function (request, response) {
    // 监听到请求之后所做的操作
    // request 对象包含:用户请求报文的所有内容
    // 我们可以通过request对象,获取用户提交过来的数据

    // response 响应对象,用来响应一些数据
    // 当服务器想要向客户端响应数据的时候,就必须使用response对象

    // 响应html代码,
    // 有些浏览器会显示乱码,可以通过设置http响应报文的响应头来解决
    response.setHeader('Content-Type', 'text/html;charset=utf-8');
    response.write('<h1>hello world!</h1>');
    response.end();
})
// 4、监听端口,开启服务
server.listen(8080, function(){
    console.log("服务器已经启动,可访问以下地址:");
    console.log('http://localhost:8080');
})

终端运行:node index.js

浏览器打开:http://localhost:8080

使用Node.js搭建一个简易服务器就是这么简单!