问题描述
我正在试用 JSON 服务器。我有一个关于在我们的 api 中使用“customids”而不是“id”的基本问题。下面是我的设置
我有一个以employeeid为id的雇员端点(不使用id)
1)db.json 看起来像
"employees": [
{
"employeeid": 1,"fname": "manju","lname": "s"
},{
"employeeid": 2,"fname": "albert","lname": "dawson"
},{
"fname": "ramesh","lname": "watsons","employeeid": 3 }]
2) 使用启动 json 服务器 json-server --id employeeid db.json
3) 如果我执行 POST,它会按预期自动生成员工 ID。在此之前一切都很好
4)如果我在不发送员工 ID 的情况下执行 PUT,则它会完全删除员工 ID 我的意思是,如果我想更新员工 ID 2 的名字(比如从 albert 到 albertin),我在下面发送 PUT 正文
PUT 网址 http://localhost:3000/employees/2
PUT Body(没有发送员工 ID。因为它是在 URL 中发送的) { "fname": "albertin","lname": "道森" }
PUT 运行成功,但如果我执行 GET,我会得到以下结果 (员工 ID 消失)
{
"employeeid": 1,"lname": "s"
},{
"fname": "albertin","lname": "dawson"
},{
"fname": "ramesh","employeeid": 3 }
]```
however,if I used an "id" instead of employeeid this used to work fine. Can anyone please explain if we can avoid sending employeeid in the body again
thanks
解决方法
你可以这样做
const employer = [{
"employeeid": 1,"fname": "manju","lname": "s"
},{
"employeeid": 2,"fname": "albert","lname": "dawson"
},{
"fname": "ramesh","lname": "watsons","employeeid": 3
}
]
const newdata = {
"employeeid": 2,"fname": "new albert","lname": "dawson"
}
const update = employer.map((x) => x.fname === "albert" ? newdata : x)
console.log(update)