【问题标题】:I receive object empty in nodejs我在nodejs中收到空对象
【发布时间】:2020-12-16 09:22:47
【问题描述】:

我收到空对象,当我使用 fetch 发送数据时,但使用邮递员我有数据,我不知道,为什么会发生这种情况?

这是我在前端的代码。

let formReset = document.querySelector('#reset-form')
    let email = document.querySelector("input[name='email']")
    let url = 'http://localhost:3000'
    var misCabeceras = new Headers();


    formReset.addEventListener('submit', (e)=>{
        let data = {
            email: email.value
        }
        fetch(url+'/forget-password', {
            method: 'POST',
            headers:misCabeceras,
            mode: 'cors'
            body: JSON.stringify(data)
        }).then(res => res.json())
        .then(data => data)
        .catch(err => console.log(err))
        e.preventDefault()
    })

在 nodejs 中:

 router.post("/forget-password",(req,res)=>{
        console.log(req.body)
    })

邮递员中的图像

如果我在标头中使用浏览器发送数据,我收到了数据,但在我的控制台或节点中为空:/,这是我第一次使用 nodejs

【问题讨论】:

  • 在浏览器的屏幕截图中,您看到的是请求,而不是响应。单击Response 时会出现什么?另外,控制台选项卡中会显示什么?
  • 作为回应,我没有答案,因为我没有返回数据,例如,我只写 console.log(req.body) 来查看 nodejs 中的数据。
  • 你有一个body-parser中间件吗?
  • @SándorBakos 是的,我有 body-parser,但我删除了 body-parser,然后我用邮递员发送数据,发现,我收到了数据,但在浏览器中没有:/

标签: node.js express fetch postman


【解决方案1】:

尝试在fetch对象中添加缺少的逗号,如下图:

fetch(url+'/forget-password', {
  method: 'POST',
  headers: misCabeceras,
  mode: 'cors',
  body: JSON.stringify(data)
}

【讨论】:

  • 在您提供的代码示例中,'cors' 后面没有逗号,这将导致错误。由于 Postman 正在工作,问题一定出在您的前端代码中。
  • 我删除了最后一个代码,我想要下一个代码,在控制台中浏览器显示 json 但在 nodejs 中我收到的数据是空的。 fetch('localhost:3000/forget-password', { method: 'POST', body: JSON.stringify({user:email.value}) }).then(res => res.json()) .then(data => data ) .catch(err => console.log(err))
  • 我不知道你之前的评论是什么意思。
  • 我删除最后一个代码,我写下一个代码 fetch('localhost:3000/forget-password', { method: 'POST', body: JSON.stringify({user:email.value}) } ).then(res => res.json()) .then(data => data) .catch(err => console.log(err)) 但我有相同的结果:/
  • 您不应删除 headersmode 键值对。
猜你喜欢
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 2018-10-17
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
相关资源
最近更新 更多