search-live
v1.0.0
Published
```javascript const fs = require('fs'); const url = require('url'); const path = require('path'); const http = require('http'); const data = JSON.parse(fs.readFileSync('./mock/data.json'));
Downloads
4
Readme
##http
const fs = require('fs');
const url = require('url');
const path = require('path');
const http = require('http');
const data = JSON.parse(fs.readFileSync('./mock/data.json'));
http.createServer((req, res) => {
//路径
let pathname = url.parse(req.url).pathname;
//根路径路径
if (pathname === '/') {
pathname = 'index.html';
}
//判断是否为文件夹
if (path.extname(pathname)) {
if (fs.existsSync(path.join('public', pathname))) {
res.end(fs.readFileSync(path.join('public', pathname)));
}
} else {
///端口
if (pathname === '/api/login' && req.method === 'POST') {
let body = ''
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
let {
username,
password,
} = JSON.parse(body);
let logFlag = data.find(item => {
return item.username === username && item.password === password;
});
if (logFlag) {
res.end('1')
} else {
res.end('0')
}
})
}
//注册端口
if (pathname === '/api/register' && req.method === 'POST') {
let regbody = '';
req.on('data', chunk => {
regbody += chunk;
});
req.on('end', () => {
let {
username,
password,
} = JSON.parse(regbody);
let Exis = data.find(item => {
return item.username === username
});
if (Exis) {
res.end('0')
} else {
data.push(JSON.parse(regbody));
fs.writeFileSync('mock/data.json', JSON.stringify(data));
res.end('1');
}
})
}
}
}).listen(8080, () => {
console.log('服务器启动');
})```