index.js

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
console.log('start')
// 导入http模块:
const http = require('http');
const fs = require('fs');
const miment = require('miment');
const port = 8081
// 创建http server,并传入回调函数:
const server = http.createServer(async (req, res) => {
// 回调函数接收req和res对象,
// 获得HTTP请求的method和url:
const url = req.url;
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
console.log(`${miment().format('YYYY-MM-DD hh:mm:ss')}======ip:${ip}======方法:${req.method}======url:${req.url}`);
res.writeHead(200, {
"Content-Type": "text/html;charset=UTF-8"
});
switch (true) {
case /favicon.ico/.test(url):
fs.readFile('favicon.ico', (err, data) => {
if (!err) {
res.writeHead(200, {
"Content-Type": "image/x-icon"
});
res.end(data)
} else {
throw err;
}
});
break;
case /^\/somekey/.test(url):
//some
break;
default:
//除上述之外操作
require('./modules/error')(req, res)
break;
}
});

function promiseexample(a) {
return new Promise((resolve, reject) => {
if (a) {
resolve
} else {
reject
}
})
}
server.listen(port, () => {
console.log(`Server is running at http://127.0.0.1:${port}/`);
});

error.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = (req, res) => {
//不知道url跳转首页
const url = req.url;
const igList = ['']
if (igList.indexOf(url) === -1) {
res.writeHead(302, {
'Location': 'https://www.meaqua.fun/'
});
} else {
res.writeHead(404, {
"Content-Type": "text/html;charset=UTF-8"
});
}
res.end();
}