【问题标题】:How to pass data from React component to node server.js?如何将数据从 React 组件传递到节点 server.js?
【发布时间】:2019-04-03 15:40:39
【问题描述】:

我一直在尝试将数据从我的 React 组件传递到节点 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");
});

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

【问题讨论】:

  • 你有app.use(express.json())app.use(bodyparser.json())之类的东西吗(需要body-parser包)
  • @naga-elixir-jar 谢谢你的提问。是的,我有。我已经更新了我的代码。你知道如何解决这个问题吗?
  • axios.post("/", { 可能需要完整的 uri,包括方案(如 http 或 https 等),如:axios.post("http://localhost:port" ...)

标签: javascript node.js reactjs react-native


【解决方案1】:

您正在从前端使用 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>

【讨论】:

  • 我在 server.js 文件中添加了上面的代码。但它甚至没有到达 app.post 中的那个 console.log。你知道如何解决这个问题吗?
  • 我在测试后进行了编辑...干净小巧的应用程序没有反应。请检查它是否适用于...
猜你喜欢
  • 2020-02-16
  • 1970-01-01
  • 2018-01-06
  • 2017-07-23
  • 2021-02-09
  • 1970-01-01
  • 2018-10-15
  • 2020-09-23
  • 2022-06-30
相关资源
最近更新 更多