express用PUT更新数据

// 后端
const express = require('express');
const app = express();
const port =3000;

// 中间件,解析JSON
app.use(express.json());

// 假设我们有一个简单的用户存储
let users = [
    {id: 1, name: 'Zoc'},
    {id: 2, name: 'John'}
];

// 处理PUT请求
app.put('/users/:id', (req, res) => {
    const userId = parseInt(req.params.id);
    const updateUser = req.body;
    // console.log(updateUser);

    // 查找用户
    const userIndex = users.findIndex(user => user.id === userId);
    if (userIndex === -1){
        return res.status(404).send('User not found');
    }

    // 更新用户信息
    users[userIndex] = {id: userId, ...updateUser};
    res.send(users[userIndex]);

});

// 启动服务器
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

// 前端
// 要更新的ID
const userId = 1;

// 要更新的用户数据
const updateUserData = {
    name: 'Cuba'
};

// 使用fetch发送PUT请求
fetch(`http://localhost:3000/users/${userId}`,{
    method: 'PUT', // 指定方法为put,通过URL传递userId
    headers:{
        'Content-Type': 'application/json'  // 内容为JSON格式
    },
    body: JSON.stringify(updateUserData)  // Object转JSON
})
.then(response => {
    if (!response.ok) {
        return response.text().then(text => {
            throw new Error(`Error ${response.status}: ${text}`);
        })
    }
    return response.json();  // 解析响应为JSON
})
.then (data => {
    console.log('User updated:', data);  // 显示更新后的数据
})
.catch(error => {
    console.error('There was a problem with the fetch operation:', error);
});
展开/折叠结果
User updated: { id: 1, name: 'Cuba' }

评论

发表评论

了解 数据控|突破是我们的每一步 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读