reactjs - req.body.something 返回未定义
问题描述
我一直在尝试使用 axios 将数据发布到我的快速服务器,当我 console.log(req.body.something) 它返回未定义时,当我 console.log(req.body) 只将此消息记录到控制台: [Object: null prototype] { '{"nameVal":"Usef","nickNameVal":"US"}': '' } 任何帮助将不胜感激。
// This My Server.js Code
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
const urlencodedparser = bodyParser.urlencoded({ extended: false });
// Use Cors As MiddleWhere
app.use(cors());
// Get The Post Request
app.post("/user", urlencodedparser, (req, res) => {
console.log(req.body.name); // returns undefined
});
app.listen(5000);
// and this the react component state along with the axios post request
state = {
nameVal: "Usef",
nickNameVal: "US"
};
handleSubmit = event => {
event.preventDefault();
const { nameVal, nickNameVal } = this.state;
axios.post("http://localhost:5000/user", { nameVal, nickNameVal },
{ headers: { "Content-Type": "application/x-www-form-urlencoded" } }
).then(res => {console.log(res)});
};
解决方案
如果您Content-Type
从 axios 请求中删除您的自定义标头,则 axios 默认将您的数据作为 JSON 发送,并且它将由您的快速 JSON 解析器中间件解析。
axios.post("http://localhost:5000/user", { nameVal, nickNameVal })
.then(res => console.log(res));
您发送到服务器的数据是nameVal
and nickNameVal
,因此尝试访问req.body.name
仍然会给出undefined
。尝试记录nameVal
,nickNameVal
而不是。
app.post("/user", (req, res) => {
console.log(req.body.nameVal, req.body.nickNameVal);
});
推荐阅读
- laravel - 调用字符串上的成员函数 sum()
- javascript - 如何使用 JQuery 减去文本框中的值?
- .net - 如何在 botapp 中使用 changefeed 刷新 cosmos db 容器中更改的缓存?
- c++ - 什么提供了 C/C++ 运行时库?
- windows - 是否可以将设备相关位图转换为正常的、可显示的位图?
- java - 在 java 中创建一个带有 2 个键的索引和键的映射
- c++ - 使用优先级队列的 K 排序数组 - C++
- java - 无法从 Java 类获取自定义注解
- java - 从外部 URL 获取 thymeleaf 片段
- android - 将环境设置为 ExternalStorageDirectory 时,无法在 android 上使用 java 创建目录文件