一、核心模块 - http模块介绍
• http 模块可以发布 web 服务,在没有学习http模块之前,我们都是用tomcat,nginx等服务器。
• 使用之前,通过 require 引入
• 官方文档:http://nodejs.cn/api/http.html
二、示例
const http = require('http')
//1.创建服务器 req = request 请求 res = response 响应
const server = http.createServer((req,res) => {
res.statusCode = 200;//表示设置请求成功的状态码
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('你好: Node.js')
})
//2.发布 web 服务
const port = 3000 //端口号
const host = 'localhost' //主机名
//在浏览器中访问: http://localhost:3000 然后能看到效果
server.listen(port,host,() => {
console.log(`服务器运行在 http://${host}:${port}`);
})