如何将数据从 React 组件传递到节点 server.js? [英] How to pass data from React component to node server.js?

查看:31
本文介绍了如何将数据从 React 组件传递到节点 server.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将数据从我的 React 组件传递到节点 server.js.在我的 React 组件中,在 componentWillMount 中,我正在进行 axios 发布调用并传递 countValue.

I have been trying to pass data from my React component to the node server.js. In my React component, inside the componentWillMount, I am making an axios post call and pass countValue.

这是我的 React 组件代码:

Here is my code for the React Component:

componentWillMount = () => {

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

在我的 server.js 中,我只是想通过 req.body.countValue 获取 countValue.但是,它始终设置为未定义".

Inside my server.js, I am simply trying to get countValue through req.body.countValue. However, it is always set to "undefined".

req.body 只是一个空对象,{}.

req.body just comes out to be empty object, {}.

这是我的 server.js 代码

Here is my code for the 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");
});

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

Could anyone please help me with this issue?

推荐答案

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

you are making POST request with axios from the frontend,

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

and configured in the server to listen to GET only...

在快递中添加:

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

很奇怪……我测试了它,它工作正常,

very strange... i tested it and it working,

如果你制作没有反应的小应用......它是否有效?

if you making small app without the react ... it's working?

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

this is the full test that worked for me:

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>

这篇关于如何将数据从 React 组件传递到节点 server.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆