express的patch

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

// 中间件,用于解析 JSON 请求体  
app.use(express.json());  

// 模拟的用户数据  
let users = [  
    { id: 1, name: 'Alice', age: 25 },  
    { id: 2, name: 'Bob', age: 30 }  
];  

// PATCH 请求处理  
app.patch('/users/:id', (req, res) => {  
    const userId = parseInt(req.params.id);  
    const user = users.find(u => u.id === userId);  

    if (!user) {  
        return res.status(404).send('User not found');  
    }  

    // 更新用户信息  
    if (req.body.name) {  
        user.name = req.body.name;  
    }  
    if (req.body.age) {  
        user.age = req.body.age;  
    }  

    res.send(user);  
});  

// 启动服务器  
app.listen(port, () => {  
    console.log(`Server running at http://localhost:${port}`);  
});
// 客户端
// 定义要更新的用户 ID  
const userId = 1;  

// 定义要发送的更新数据  
const updateData = {  
    name: "Culi"  
};  

// 使用 fetch 发送 PATCH 请求  
fetch(`http://localhost:3000/users/${userId}`, {  
    method: 'PATCH', // 指定 PATCH 方法  
    headers: {  
        'Content-Type': 'application/json' // 设置请求头为 JSON  
    },  
    body: JSON.stringify(updateData) // 将更新数据转换为 JSON 字符串并作为请求体发送  
})  
.then(response => {  
    if (!response.ok) {  
        throw new Error('Network response was not ok');  
    }  
    return response.json(); // 解析响应为 JSON  
})  
.then(data => {  
    console.log('User updated successfully:', data); // 处理成功响应  
})  
.catch(error => {  
    console.error('There was a problem with the fetch operation:', error); // 处理错误  
});
展开/折叠结果
User updated successfully: { id: 1, name: 'Culi', age: 25 }

评论

发表评论

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

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

继续阅读