javascript - 从 React.js 组件到 Node.js 服务器的 POST 请求出现问题

标签 javascript node.js reactjs

我正在尝试将基于 React.js 的客户端输入数据发送到用 Node.js 编写的服务器,后者将其放入数据库。我没有错误,提交后,新记录显示在数据库中,但它们是空的。我有两个输入,我将它们连接到一个字符串中并尝试将其发送到数据库(因此数据库有一个属性)。你能检查我的代码看看有什么问题吗?也许有标题的东西......

这是 React 组件中的函数:

  addCompetitor = event => {
    event.preventDefault();
    const name = this.state.draftCompetitorName;
    const lastname = this.state.draftCompetitorLastname;
    fetch(`http://localhost:5000/competitors`, {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ name: `${name}${lastname}` })
    })
      .then(response => response.json())
   };

这是服务器 POST 响应:

  app.post("/competitors/", urlencodedParser, function (req, res) {
    const newCompetitor = new Competitor({ name: req.body.name });
    newCompetitor.save().then(competitor => res.json(competitor));
  });

这是应用程序配置:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type",
    "X-Requested-With"
  );
  res.setHeader("Access-Control-Allow-Credentials", true);
  next();
});

最佳答案

如果没有先安装bodyparser 。这会在处理程序之前解析中间件中传入的请求正文,该正文将在 req.body 属性下可用。

app.use(bodyParser.json({
  limit: '50mb',
  parameterLimit: 100000
}))

或者您正在使用的 Express 版本是什么?是否大于4.16?那么你也可以使用

app.use(express.json()); 

参见注释here

https://expressjs.com/en/api.html#express.json

修改代码

let databody = {
        "name": `${name}${lastname}`,
        "otherprop": this.state.otherprop
}

来自前端使用 正文:JSON.stringify(databody),

在 Express 端删除 urlencodedParser ,应如下所示:

app.post("/competitors", function (req, res) {
    console.log(req.body);
});

关于javascript - 从 React.js 组件到 Node.js 服务器的 POST 请求出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53866318/

相关文章:

reactjs - 开 Jest 测试打开 react 选择菜单

javascript - 为什么组件每次收到不同的 key 时都会卸载?

javascript - Twitter Bootstrap 模式,HTML 还是 Javascript?

node.js - Memcached 无法连接到远程服务器 | memcached.js

javascript - 同步动画,或在动画中途调用

javascript - TypedArray 和 ArrayBuffers(node/chrome)上的 Object.freeze() 未按预期工作

node.js - 如何在 Mongoose 中更新?

javascript - 对象作为 React 子对象无效(找到 : object with keys)

javascript - window.onbeforeunload 在 Chrome 中不起作用

javascript - 在 Redux reducer 中更新和重新定位数组中的对象