Lyrics


< More and better />


react fetch post node的坑

首先这个坑很是头疼,其次感谢大佬的帮助

原因

  1. fetch : body不可以传递对象

正确代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fetch('http://localhost:3800/submit',{
method:'POST',
body:JSON.stringify(data), //这是一个坑
headers: {
'Accept': 'application/json', 'Content-Type': 'application/json'
},
mode:'cors'//默认跨域,可以不写(因为我需要跨域)
})
.then(function(response){
response.status //=> number 100–599
response.statusText //=> String
response.headers //=> Headers
response.url
console.log(response.status, response.url,response.headers);
},function(error){
console.log(error.message)
})
  1. node 后台接收post 数据需要body-parse 的解析,原因:express req上面是没有body 属性的

后端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type, Accept");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.post('/submit',(req,res)=>{
console.log(req.body)
}

还需锻炼 ! Fighting ~~END