js练习--用户管理API

需要node.js运行环境,创建2个文件:user.js,server.js

user.js:

let users = {};
module.exports = users;

server.js:

const http = require('http');

// 导入user模块
let users = require('./user');

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    // 设置响应头部
    res.setHeader('Content-Type', 'application/json');

    // 解析请求URL和Method
    const url = req.url;
    const method = req.method;

    // 处理POST请求(注册用户)
    if (url === '/register' && method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString(); // 转换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请求(查询用户)
    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));
        }
    }
    // 其他请求
    else {
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Not Found' }));
    }
});

// 服务器监听3000端口
server.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

 

posted @ 2024-08-28 10:49  morein2008  阅读(8)  评论(0编辑  收藏  举报