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