javascript - 如何将数据从React组件传递到node server.js?

标签 javascript node.js reactjs react-native

我一直在尝试将数据从我的 React 组件传递到 Node server.js。 在我的 React 组件中,在 componentWillMount 内部,我正在进行 axios post 调用并传递 countValue。

这是我的 React 组件代码:

componentWillMount = () => {

    axios.post("/", {
      countValue: 12
    });
  }

在我的 server.js 中,我只是尝试通过 req.body.countValue 获取 countValue。但是,它始终设置为“未定义”。

req.body 只是空对象,{}。

这是我的 server.js 代码

const express = require('express');
const bodyParser = require('body-parser');
const engines = require('consolidate');
const app = express();

app.engine("ejs", engines.ejs);
app.set('views', __dirname);
app.set("view engine", "ejs");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", (req, res) => {
    console.log(req.body.countValue);
    res.render("index");
});

有人可以帮我解决这个问题吗?

最佳答案

您正在前端使用 axios 发出 POST 请求,

并在服务器中配置为仅监听 GET...

在 express 中添加:

app.post("/", (req, res) => {
    console.log(req.body.countValue);
    res.render("index");
});

非常奇怪...我测试了它并且它工作正常,

如果你在没有反应的情况下制作小型应用程序......它可以工作吗?

这是对我有用的完整测试:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.render('so');
});

app.post('/', (req, res) => {
    console.log("countValue =", req.body.countValue);
    res.render('so');
});
app.listen(3000, () => {
    console.log('app now listening on port 3000');
});

和 HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SO</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script type="text/javascript">
    axios.post("/", {
        countValue: 12
    });
</script>
</head>
<body>

</body>
</html>

关于javascript - 如何将数据从React组件传递到node server.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499112/

相关文章:

javascript - 响应式侧边栏选项卡和点击事件切换

javascript - 请告诉我这个简单的代码有什么问题

javascript - sequelize 创建或更新关联

javascript - jQuery : Removing parent tag not the child of that parent

node.js - 在 Node.js 中使用集群时出现错误

javascript - 如何使用 webpack 服务器端处理静态 Assets ?

unit-testing - 您如何编写涉及数据库的单元测试?

reactjs - React Redux : More containers v. 秒。更少的容器

javascript - 使用 ReactJS 将数据从一个组件传递到另一个组件

javascript - React Native - 如何在多个按钮上应用 Prop