【发布时间】:2017-12-02 08:50:34
【问题描述】:
我正在尝试对节点中的 json-server 提供的 json 文件执行 POST 操作。我在尝试执行上述 POST 操作时收到以下 500 错误:
"TypeError: 无法读取未定义的属性 'id' 在 Function.createId"
post操作如下:
pushState = () => {
var update = {
"a": 1,
"b": 2
};
return fetch(url, {
mode: 'cors',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(update)
})
.then((response) => {
console.log(response);
response.text();
})
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
console.log(error);
})
.done();
}
我是否正确地执行了 POST 请求?
编辑:添加异步和等待后,我仍然收到相同的错误:
pushState = async () => {
var update = {
"a": 1,
"b": 2
};
var result = await fetch(url, {
mode: 'cors',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(update)
})
.then((response) => {
console.log(response);
return response;
})
.catch((error) => {
console.log(error);
});
return result;
}
【问题讨论】:
-
我认为这可能是服务器问题,尝试通过更新传递 id?
var update = { id: 1, a: 1, b: 2 }; -
添加和 ID 字段有效!是否有需要 id 字段的原因?如果我调用的 API 没有 id 字段,或者有不同名称的 ID 字段怎么办?
-
我相信这只是因为您使用的是 json-server 并且设置的方式是寻找一个 id,这就是为什么它说“TypeError: Cannot read property 'id' of undefined在 Function.createId”。并非所有 API 都需要 id,但使用 id 更好地跟踪数据是一种很好的做法。
标签: javascript json react-native fetch json-server