1、搭建服务器 (http模块)
1、搭建服务器要使用http模块,http模块,可以创建服务器对象,同时,可以处理请求和响应
1)、引入http模块
let http = require('http')
2)、创建web服务 返回http对象
let app = http.createServer((req,res)=>{
req 请求体(请求对象) 浏览器->服务器,服务器端把浏览器发送来的信息整理到req对象里。
req.url 地址 提取地址栏数据
req.on('data') 提取非地址栏数据 所有的http[s]都会触发end事件
req.on('end')
res 响应体(响应对象) 服务器->浏览器,服务器端给浏览端发送的信息都整理在res里。
res.writeHead(200,{
'Content-Type':'text/html;charset=utf-8'});响应头设置
res.write(字符/数据<string><buffer>) 返回数据
res.end() 结束响应 必须
})
3)、监听服务器
app.listen(端口,[地址],[回调])
端口: 1-65535 1024以下系统占用
地址:localhost 真实域名xx.duapp.com,ip地址也行。
回调:监听成功,回调一次
4)、启动服务器的命令:
node 文件名
搭建服务器的示例代码:
// 1、引入http模块(nodeJS官方的模块,是个对象)
const http = require("http");
// 2、创建服务器对象
let server = http.createServer((req,res)=>{
// req:请求对象(包含所有前端请求的信息,如:url,method,)
console.log("req.url",req.url);
console.log("req.method",req.me