首页 > 解决方案 > 将数据从反应传递到节点服务器

问题描述

我正在尝试将反应与节点集成,因此在从反应端向节点发送数据时,我总是未定义,请查看以下代码(获取请求工作正常!)

反应面

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

标签: javascriptnode.jsreactjs

解决方案


问题 1

你正在使用fetch,不是jQuery。请求正文的内容放在一个名为bodynot的属性中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)

推荐阅读