【问题标题】:How to get request body in post Express?如何在 post Express 中获取请求正文?
【发布时间】:2020-11-08 11:12:51
【问题描述】:

我有一个在提交表单时发出 POST 请求的应用程序。但是当请求在服务器上时,我无法获取请求的正文。

这是我的 ReactJS 代码:

const onSubmit = async event => {
  try {
    event.preventDefault()
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      mode: 'no-cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    })
    const result = await response.json()
  } catch (e) {
    console.error(e)
  }
}

return (
  <>
    <h1>Authorisation</h1>
    <form onSubmit={onSubmit}>
      <input name="email" value={email} onChange={e => setEmail(e.target.value)} />
      <input name="password" value={password} onChange={e => setPassword(e.target.value)} type="password"/>
      <button type="submit">Submit</button>
    </form>
  </>
)

在我的后端我有 Express:

app.use(express.json())

const login = async (req, res) => {
  try {
    console.log(req.body)              // here is always {}
    const {email, password} = req.body
    /*some code*/
  } catch (e) {
    console.log('Login error: ' + e)
  }
}

router.post('/login', login)
app.use(router)

【问题讨论】:

  • 你能从快递服务器发布完整的代码吗?你在哪里定义路由 /login?
  • 前端代码看起来不错。请发布完整的快递端服务器代码。我认为你在那里遗漏了一些东西。

标签: node.js reactjs express fetch


【解决方案1】:

我注意到您正在使用 no-cors 模式。当您使用该模式时,它会限制某些标题。

例如,这种模式只允许Content-Type 变为application/x-www-form-urlencoded、multipart/form-data 或text/plain。你可以阅读更多here

我建议你只使用cors 模式,这样你就可以使用application/json

【讨论】:

  • 我明白了,我改变了cors模式的类型,谢谢。但它没有帮助,有相同的输出
  • 有意思,能不能把模式去掉,看看会发生什么?
  • 是的,没有变化
  • 嗨,迈克,你能告诉我们你的反应 useState 电子邮件和密码挂钩吗?
  • 我想知道为什么它以前不起作用,现在一切正常,谢谢
猜你喜欢
  • 1970-01-01
  • 2018-08-17
  • 2014-01-27
  • 2017-09-02
  • 2019-06-26
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多