js練習(xí)--用戶管理API
需要node.js運(yùn)行環(huán)境,創(chuàng)建2個(gè)文件:user.js,server.js
user.js:
let users = {};
module.exports = users;
server.js:
const http = require('http');
// 導(dǎo)入user模塊
let users = require('./user');
// 創(chuàng)建HTTP服務(wù)器
const server = http.createServer((req, res) => {
// 設(shè)置響應(yīng)頭部
res.setHeader('Content-Type', 'application/json');
// 解析請(qǐng)求URL和Method
const url = req.url;
const method = req.method;
// 處理POST請(qǐng)求(注冊(cè)用戶)
if (url === '/register' && method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // 轉(zhuǎn)換Buffer到字符串
});
req.on('end', () => {
try {
const { username, password } = JSON.parse(body);
if (users[username]) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Username already exits' }));
} else {
users[username] = { username, password };
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'User registered successfully' }));
}
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Invalid json' }));
}
});
}
// 處理GET請(qǐng)求(查詢用戶)
else if (url.startsWith('/user/') && method === 'GET') {
const username = url.split('/')[2];
const user = users[username];
if (!user) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'User not found' }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(user));
}
}
// 其他請(qǐng)求
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Not Found' }));
}
});
// 服務(wù)器監(jiān)聽(tīng)3000端口
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});

浙公網(wǎng)安備 33010602011771號(hào)