javascript - 将数据从反应传递到节点服务器
问题描述
我正在尝试将反应与节点集成,因此在从反应端向节点发送数据时,我总是未定义,请查看以下代码(获取请求工作正常!)
反应面
export default class customers extends Component {
postcustomer(){
customers=[{id:1,name:'xws'},{id:2,name:'sfg'}]
fetch('/form', {
method: 'post',
data: JSON.stringify(customers)
}).then(res=>res.json()).then(res=>console.log(res))
}
componentDidMount() {
this.postcustomer()
}
render() {
return (
<div>
</div>
);
}
}
然后在节点服务器中
const express=require('express')
const app=express()
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.post('/form',(req,res)=>{
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
console.log(req.body.data)
})
app.listen(5000)
所以一旦我运行 nodemon server.js req.body.data 给我 undefined
解决方案
问题 1
你正在使用fetch
,不是jQuery
。请求正文的内容放在一个名为body
not的属性中data
问题 2
您忘记指定 Content-Type,因此 fetch 将默认声明它正在发送纯文本。
const customers=[{id:1,name:'xws'},{id:2,name:'sfg'}];
fetch('/form', {
method: 'post',
body: JSON.stringify(customers),
headers: {
"Content-Type": "application/json"
}
})
.then(res=>res.json())
.then(res=>console.log(res))
在旁边。不要使用隐式全局变量。const
用, let
(或也许)声明变量var
。
问题 3
console.log(req.body.data)
您的 JSON 在它的任何地方都没有data
属性。顶层对象是一个数组。
console.log(req.body)
推荐阅读
- javascript - document.querySelector reading only 1 class
- android - 翻译动画部分的屏幕变为空白
- .htaccess - 需要为 uri 后端添加基本身份验证,但需要排除一些 uri
- mysql - 错误 1005 (HY000): 无法创建表 'people.googlea' (errno: 150)
- c# - 起订量:FileNotFoundException:无法加载文件或程序集“System.Runtime”
- javascript - Highcharts 限制将在 yAxis 上的类别中显示的项目数量
- azure - POST JSON 以将事件记录到 Application Insights
- postgresql - 如何从postgresql中表的更改列的结果中查询
- c++ - 如何避免此 C++ 代码中的算术异常?
- php - laravel中的redis问题