【问题标题】:Passing the params using react fetch not working使用 react fetch 传递参数不起作用
【发布时间】:2017-05-15 23:35:53
【问题描述】:

这是服务器控制器(有效)

function logTheRequest(req, res) {
  console.log(req.body);
  res.sendStatus(200);
}

这是客户端获取

newCustomer() {
  fetch('/customers/sign-up', {
    method: 'POST',
    body: 'test',
  });
}

但是当我 console.log(req.body) 时,我得到的只是 { }

【问题讨论】:

  • 我认为它可能需要 json。您是否尝试传递 contentType 标头('application/text')?
  • 刚刚尝试使用 headers: { 'Content-Type': 'application/text' },它仍然显示 body { }。感谢您提供建议! :)
  • 那你可能有一个错误的 nodejs 配置。检查网络标签,看看数据是否正确发送。
  • 我应该在 github repo 上提出问题吗?它是 react-starter-kit。适用于 application/json,但不适用于 application/text
  • 如果您使用的是-github.com/kriasoft/react-starter-kit,请检查github.com/kriasoft/react-starter-kit/blob/master/src/server.js。它有这行配置:app.use(bodyParser.json());

标签: javascript reactjs fetch


【解决方案1】:

req.body 一直空着回来,直到我将 app.use(bodyParser.json() 添加到我的 server.js 文件中。确保导入body-parser

看起来原因是因为bodyParser在req.body:https://github.com/expressjs/body-parser下的中间件中解析请求体。关于 bodyParser 的更多详细信息:What does `app.use(bodyParser.json())` do?

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多