【问题标题】:Unexpected end of JSON input when trying to execute axios post request尝试执行 axios 发布请求时 JSON 输入意外结束
【发布时间】:2021-03-03 20:07:26
【问题描述】:

我收到此错误 -

"SyntaxError: C:\Users\ts\Desktop\react projects\tasks\server\cards.json: Unexpected end of JSON input"

我看到了很多解决此错误的方法,但无法提出解决方案。 当我尝试将新对象添加到具有 JSON 对象数组的 JSON 文件时出现此错误。

JSON 文件示例-

    [{"number":12,
      "color":"blue"},
     {"number":10,
      "color":"red"}
    }]

即将写入文件的卡示例-

    {
    "number":10,
    "color":"blue"
    }

客户请求-

    const cloneTicket = (ticket: Ticket) => {    
        axios.post(APIRoot+'/clone/card', card).then((response) => {
            console.log(response);
        }, (error) => {
            console.log(error.response.data);
        });
    }

服务器 -

    app.post(APIPath + '/clone/card', (req, res) => {
      const cards = fs.readFileSync('cards.json');
      let cards_json = JSON.parse(cards)
      
      cards_json.push(req.body)
    
      const new_jsons = JSON.stringify(cards_json,null,2)
    
      fs.writeFileSync('cards.json', new_jsons, (res:any)=>{
        console.log(res)
      })
      res.send(new_jsons)
    })

cards.json 文件-

[
    {
        "number": 12,
        "color": "blue"
    },
    {
        "number": 10,
        "color": "red"
    }

]

以及从 \server\cards.json 抛出的错误。

【问题讨论】:

  • 该示例不是有效的 JSON。 (编辑:现在是)
  • @MetByrdy 我不明白,那些例子没有使用有效的 JSON?
  • json 中的单引号并不是真正有效的,你也忘了在红色的末尾有一个 :)
  • @tsilver 既然 JSON 示例是正确的,您是否仍然遇到同样的错误?

标签: javascript axios http-post


【解决方案1】:

我想我找到了解决方法,更改此行:

const cards = fs.readFileSync('cards.json');

const cards = fs.readFileSync('cards.json', 'utf8');

当您不向readFileSync 提供编码类型时,它将返回一个缓冲区而不是文件内容。然后缓冲区将无法正确JSON.parse()ed。

文档:https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

【讨论】:

  • 那么错误可能不在您的示例 JSON 文件中。你得到什么错误?
  • 我将更新后的 JSON 文件添加到原始问题消息中
  • cards 里面有什么?你能做一个console.log并分享输出吗?直接从控制台
  • cards= cards_json= [ { number: 12, color: 'red' }, { number: 10, color: 'blue' } ]
  • 注意redblue 的单引号
猜你喜欢
  • 2016-12-17
  • 2021-11-15
  • 2023-03-15
  • 2020-07-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
相关资源
最近更新 更多