2022-11-26 16:20:22 +08:00
|
|
|
|
const sleepTime = 0; // 模拟弱网环境等待时间
|
|
|
|
|
|
2022-11-22 12:44:40 +08:00
|
|
|
|
// 1. 导入http模块
|
|
|
|
|
const http = require("http");
|
|
|
|
|
|
|
|
|
|
// 2. 创建一个web服务器对象
|
|
|
|
|
const server = http.createServer();
|
|
|
|
|
|
|
|
|
|
// 3. 监听请求事件
|
2022-11-26 16:20:22 +08:00
|
|
|
|
server.on("request", async (req, res) => {
|
2022-11-22 12:44:40 +08:00
|
|
|
|
//req-->request 请求对象, res-->response 响应对象
|
|
|
|
|
// 通过响应头设置返回前台数据格式及编码。(解决中文乱码的问题)
|
|
|
|
|
// res.setHeader('Content-Type', 'text/html;charset=utf-8');
|
|
|
|
|
//res.write()表示向客户端输出的方法
|
|
|
|
|
// res.write("hello world,你好nodejs")
|
|
|
|
|
|
|
|
|
|
res.setHeader('Content-Type', 'text/json;charset=utf-8');
|
|
|
|
|
|
|
|
|
|
let result = {};
|
|
|
|
|
if (req.url.startsWith('/user/login')) {
|
|
|
|
|
result = {
|
2022-11-23 20:37:35 +08:00
|
|
|
|
success: true,
|
2022-11-22 12:44:40 +08:00
|
|
|
|
msg: "登录成功",
|
2022-11-23 20:37:35 +08:00
|
|
|
|
data: {
|
|
|
|
|
userInfo: {
|
|
|
|
|
"id": 1,
|
|
|
|
|
"username": "root",
|
2022-11-26 13:38:30 +08:00
|
|
|
|
"realname": "真实姓名",
|
2022-11-23 20:37:35 +08:00
|
|
|
|
"idNumber": null,
|
|
|
|
|
"phoneNumber": null,
|
|
|
|
|
"role": 1,
|
|
|
|
|
"buildingId": null,
|
|
|
|
|
"doorplate": null,
|
|
|
|
|
"permission": "0",
|
|
|
|
|
"permissionTime": null
|
|
|
|
|
}
|
2022-11-22 12:44:40 +08:00
|
|
|
|
}
|
2022-11-23 20:37:35 +08:00
|
|
|
|
// success: false,
|
2022-11-22 12:44:40 +08:00
|
|
|
|
// msg: "用户名或密码不正确",
|
2022-11-23 20:37:35 +08:00
|
|
|
|
// data: null
|
2022-11-22 12:44:40 +08:00
|
|
|
|
};
|
|
|
|
|
} else {
|
|
|
|
|
result = {
|
2022-11-26 16:20:22 +08:00
|
|
|
|
success: false,
|
2022-11-22 12:44:40 +08:00
|
|
|
|
msg: "服务器内部错误",
|
2022-11-26 16:20:22 +08:00
|
|
|
|
data: null,
|
|
|
|
|
// extra: {
|
|
|
|
|
// url: req.url,
|
|
|
|
|
// method: req.method,
|
|
|
|
|
// headers: req.headers,
|
|
|
|
|
// req: Object.keys(req),
|
|
|
|
|
// res: Object.keys(res)
|
|
|
|
|
// }
|
2022-11-22 12:44:40 +08:00
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
res.write(JSON.stringify(result));
|
|
|
|
|
|
2022-11-26 16:20:22 +08:00
|
|
|
|
// 模拟弱网等待时间
|
|
|
|
|
await new Promise((resolve) => {
|
|
|
|
|
setTimeout(resolve, sleepTime);
|
|
|
|
|
})
|
|
|
|
|
|
2022-11-22 12:44:40 +08:00
|
|
|
|
//res.end()每次响应完,需要调用此方法 来结束响束
|
|
|
|
|
res.end();
|
2022-11-26 16:20:22 +08:00
|
|
|
|
console.log(new Date(), "req.url", req.url);
|
2022-11-22 12:44:40 +08:00
|
|
|
|
})
|
|
|
|
|
|
2022-11-26 00:48:09 +08:00
|
|
|
|
// 4. 监听端口,为了避免端口冲突,这里给一个本机端口
|
|
|
|
|
server.listen(80, () => {
|
|
|
|
|
let baseUrl = 'http://localhost:80';
|
2022-11-22 12:44:40 +08:00
|
|
|
|
console.log(`服务启动成功: ${baseUrl}/`);
|
|
|
|
|
console.log();
|
|
|
|
|
console.log(`${baseUrl}/user/login`);
|
|
|
|
|
})
|