[英]Uncaught (in promise) SyntaxError: Unexpected end of JSON input on my console
我的控制台返回: 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))
})
这是我的 controller:
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)
}
})
}, [])
你定义req.params.categoryId,顺便说一下是字符串。 因此,当您执行 function getCat 并将其定义为 object 时,它会返回错误。
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 定义为 object 并使用原始 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))
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.