const http = require('http');
const fs = require('fs');
const app = http.createServer((req, res) => {
const [url, query] = req.url.split('?');
const books = fs.readFileSync('./data/books.json');
const bookList = JSON.parse(books);
if (req.method === 'GET' && url === '/api/getbooks') {
res.end(books);
} else if (req.method === 'POST' && url === '/api/addbook') {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const params = parseURL(body);
params.id = Date.now();
bookList.push(params);
fs.writeFileSync('./data/books.json', JSON.stringify(bookList));
res.end('post数据提交成功');
});
} else if (req.method === 'DELETE' && url === '/api/delbook') {
const { id } = parseURL(query);
const index = bookList.findIndex((value) => {
return value.id == id;
});
if (index === -1) {
res.end('找不到你要删除的元素');
} else {
bookList.splice(index, 1);
fs.writeFileSync('./data/books.json', JSON.stringify(bookList));
res.end('删除');
}
} else if (req.method === 'PUT' && url === '/api/updatebook') {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const params = parseURL(body);
console.log(params);
const index = bookList.findIndex((value) => value.id == params.id);
if (index === -1) {
res.end('要修改的元素不存在 请检查重试');
} else {
bookList[index] = { ...bookList[index], ...params };
fs.writeFileSync('./data/books.json', JSON.stringify(bookList));
res.end('修改');
}
});
} else {
res.end('xxxxx');
}
});
app.listen(8888, () => console.log('8888端口开启成功'));
function parseURL(query) {
const usp = new URLSearchParams(query);
let obj = {};
usp.forEach((value, key) => (obj[key] = value));
return obj;
}