首页 > 解决方案 > 反应:对 JSON 服务器的 POST Fetch 请求导致 TypeError:无法读取未定义的属性“id”

问题描述

我正在尝试使用 JSON 服务器将对象写入 db 文件;但是,JSON 服务器不断给出错误:TypeError: Cannot read property 'id' of undefined。

我可以使用 Fetch 成功读取文件,它只是我遇到此问题的 POST。有任何想法吗?

JSON-服务器错误消息

//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);
  }
}

标签: javascriptreactjsjson-server

解决方案


推荐阅读