【发布时间】:2021-05-15 21:39:37
【问题描述】:
我的后端终端返回null 和TypeError: Cannot read property 'categories' of null,我的代码缺少什么?它还会在我的控制器上的 console.log(user) 上返回 null
这是我的功能:
function addCategory(e) {
e.preventDefault();
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({
name: name,
description: description,
type: type,
amount: amount
})
})
.then(res => {
return res.json()
})
.then(data => {
if (data === true){
Swal.fire({
title: "Category added!",
icon: "success",
})
Router.push('/category')
} else {
Router.push('/errors/1')
}
})
}
这是我的路线:
router.post('/', auth.verify, (req, res) => {
const user = auth.decode(req.headers.authorization)
CategoryController.addCategory(req.body)
.then(result => res.send(result))
})
这是我的控制器:
module.exports.addCategory = (params) => {
return User.findById(params.userId)
.then((user, err) => {
console.log(user)
if(err) return false
user.categories.push(params)
return user.save()
.then((updatedUser, err) => {
return err ? false : true
})
.catch(err => {
console.log(err)
})
})
.catch(err => {
console.log(err)
})
}
这是终端错误:
【问题讨论】:
-
@yochanansheinberger 先生,我试过了,现在它返回一个不同的错误
Error: data and salt arguments required -
您传递给
CategoryController.addCategory的请求正文不包含userId参数,这意味着User.findById(params.userId)将找不到任何用户。尝试在您的请求中传递一个有效的userId。 -
@juliomalves 先生,我应该这样做吗? ` body: JSON.stringify({ name: name, description: description, type: type, amount: amount })`
-
可以,只要是有效的
userId。
标签: javascript node.js api next.js