繁体   English   中英

如何将数据从React组件传递到节点server.js?

[英]How to pass data from React component to node server.js?

我一直在尝试将数据从我的React组件传递到节点server.js。 在我的React组件中,在componentWillMount内部,我正在进行axios后期调用并传递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 ...

在快递中添加:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM