【问题标题】:TypeError: Cannot read property 'categories' of nullTypeError:无法读取 null 的属性“类别”
【发布时间】:2021-05-15 21:39:37
【问题描述】:

我的后端终端返回nullTypeError: 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


【解决方案1】:

您正在向后端对象发送:名称、描述、类型和数量,但不使用 userId 属性。在后端,您的 find 调用然后返回 null。 Find 正在尝试获取具有未定义值的用户。

【讨论】:

  • 它在我的控制台上返回未定义的“userId”.. 先生,我该怎么做?
猜你喜欢
  • 2020-01-29
  • 2022-01-12
  • 2021-12-04
  • 2021-12-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多