javascript - 反应:对 JSON 服务器的 POST Fetch 请求导致 TypeError:无法读取未定义的属性“id”
问题描述
我正在尝试使用 JSON 服务器将对象写入 db 文件;但是,JSON 服务器不断给出错误:TypeError: Cannot read property 'id' of undefined。
我可以使用 Fetch 成功读取文件,它只是我遇到此问题的 POST。有任何想法吗?
//this is the function where I perform the POST
const handleSubmit = (e) => {
e.preventDefault();
setSubmitted('t');
setIsPending(true);
const arg = { filename, trialId, hash, location, author, submitted };
fetch('http://localhost:8000/args/', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(arg)
}).then(() => {
console.log('new file added');
})
};
//This is my current db file:
{
"args": [
{
"filename": "Accelerometer",
"trialId": "01",
"hash":"",
"author": "",
"location": "IPFS",
"submitted": "f"
}
]
}
// 这是我用来从 db 页面读取的数据。
setTimeout(() => {
fetch('http://localhost:8000/args', { signal: abortCont.signal })
.then(res => {
//check response for error
if (!res.ok) {
throw Error('Error when fetching data');
}
return res.json();
})
.then(data => {
setArgs(data);
setIsPending(false);
setError(null);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('fetch aborted');
} else {
setError(err.message);
setIsPending(false);
}
})
}, 1500);
// 这是服务器中的函数 Function.createID 似乎有问题。
function createId(coll) {
const _ = this;
const idProperty = _.__id();
if (_.isEmpty(coll)) {
return 1;
} else {
let id = _(coll).maxBy(idProperty)[idProperty]; // Increment integer id or generate string id
return _.isFinite(id) ? ++id : nanoid(7);
}
}
解决方案
推荐阅读
- c# - 在数据库中插入 XML 数据
- flask - Flask - Create and upload files into folders dynamically
- sql - Oracle SQL 中的子字符串
- java - MessageQueue 回调中的异常:用于录音机的 handleReceiveCallback
- azure-virtual-machine - 具有模板部署的 Azure VM 扩展 Powershell DSC - 配置重新启动时进程失败
- scala - 如何处理 Some[String] 参数?
- java - 在给定超时时跳过蚂蚁目标
- android - 将运行时添加的视图与 MVVM 中的数据绑定
- asp.net-mvc - 通过 asp.net MVC 在视图页面中显示 Webapi 对象
- c++ - 没有预处理器的调用方法/文件的文件名/行号