-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathapp_old.js
More file actions
78 lines (72 loc) · 2.29 KB
/
app_old.js
File metadata and controls
78 lines (72 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* author:sunquan
* 2021/09/27
* 本文件实现一个静态服务器,对于文件类请求直接响应展示,对于Ajax类请求转发并响应对应数据;
* 未使用express框架,不能识别压缩后的文件。故弃用,目前使用serve.js
*/
let http = require('http');
let url = require('url');
let fs = require('fs');
let mime = require('mime');
let path = require('path');
let axios = require('axios');
let server = http.createServer((req, res) => {
let pathname = url.parse(req.url).pathname,
UrlType = pathname.split('/'), //辨别请求是不是ajax,本应用ajax请求都有aqi标记,具体使用时需要根据情况修改此处
ext = path.parse(pathname).ext,
post = '',
newPathName,
mimeType = mime.getType(ext);
if (UrlType[1] == 'api' || UrlType[1] == 'snake') {
//我的前端请求接口url需要代理,url会添加api,需要将url替换并转发;如果为snake请求另外一个端口号
if(UrlType[1] == 'api'){
newPathName = pathname.replace(/\/api/, 'http://39.104.22.73:8888');
}else {
newPathName = pathname.replace(/\/snake/, 'http://39.104.22.73:8081');
}
req.on('data', function (chunk) {
post += chunk;
});
req.on('end', function () {
axios.post(
newPathName,
JSON.parse(post)
).then(function (response) {
res.end(JSON.stringify(response.data));
}).catch(function (e) {
console.log('ajax error');
});
});
} else if (UrlType[1] == '') {
ReadAndResponse('index.html',res,mimeType);
} else {
ReadAndResponse(pathname.substring(1),res,mimeType);
}
});
server.listen(68);
/**
* 读取文件,并在服务中响应对应的文件
* @param filePath 文件路径
* @param response 响应对象
* @param fileType 文件类型
* @constructor
*/
function ReadAndResponse(filePath,response,fileType){
fs.readFile(filePath, (err, data) => {
if (err) {
// 错误就返回404状态码
response.writeHead(404, {
'Content-Type': fileType
})
} else {
// 成功读取文件
response.writeHead(200, {
'Content-Type': fileType
})
// 展示文件数据
response.write(data);
}
// 注意,这个end 一定要放在读取文件的内部使用
response.end();
});
}