【问题标题】:Uncaught (in promise) SyntaxError: Unexpected end of JSON input on my consoleUncaught (in promise) SyntaxError: Unexpected end of JSON input on my console
【发布时间】:2021-06-01 17:20:20
【问题描述】:

我的控制台返回:Uncaught (in promise) SyntaxError: Unexpected end of JSON input,我的终端返回:{ categoryId: undefined }

这是我的路线:

router.get('/getAll', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization);
    const categoryId = req.params.categoryId
    UserController.getCat({ categoryId })
  .then(category => res.send(category))
})

这是我的控制器:

module.exports.getCat = (params) => {
    console.log(params)
    return User.findById(params.categoryId)
   .then(resultFromFindById => resultFromFindById)
}

我想在我的组件上使用此 fetch 获取所有数据,请帮助我找出问题所在.. 似乎我的语法没有问题

useEffect(() => {
    fetch(`${process.env.NEXT_PUBLIC_API_URL}/users/getAll`, {
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
    })
    .then(res => res.json())
    .then(data => {
        if(data) {
            console.log(data)
        } 
    })
}, [])

【问题讨论】:

  • 取消缩进 .then 子句真的令人眼花缭乱。您可以使用async 功能吗?如果是这样,您可以 await 处理它。
  • 您需要解决“未捕获的承诺”问题才能找出实际问题。将 .catch() 附加到您的承诺链的末尾,或者使用 await 代替。
  • @tadman 我现在明白了,先生,我的语法没有问题.. 只是我的`.findById` 应该只是.find 谢谢你的努力顺便说一句:)

标签: javascript node.js reactjs api


【解决方案1】:

你定义req.params.categoryId,顺便说一下是字符串。因此,当您执行函数 getCat 并将其定义为对象时,它会返回错误。

router.get('/getAll', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization);
    const categoryId = req.params.categoryId // this categoryId is string
    UserController.getCat({ categoryId }) // you define it inside curly bracket and hope it treats as object, so this causes error
  .then(category => res.send(category))
})

将 categoryId 定义为对象并使用原始 json 主体的更好方法,它看起来像这样:

router.get('/getAll', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization);
    // this param variable means object and use it in function getCat
    const param = {
      categoryId: req.body.categoryId
    }
    UserController.getCat(param)
  .then(category => res.send(category))
})

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 2021-11-06
    • 2019-08-31
    • 1970-01-01
    • 2019-09-19
    • 2019-11-21
    • 2021-08-23
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多