react 处理fetch网络请求
1、通过node.js搭建服务器,且必须有跨域请求
2、php搭建的不行,估计是跨域的问题
3、在页面渲染后的componentDidMount()生命周期函数中发送请求
代码示例:
react.js文件
import React ,{ Component}from 'react';
import User from './user'
class App extends React.Component {
constructor()
{
super();
}
componentDidMount()
{
var flag=false;
if(flag)
{
fetch('http://localhost:3000/news')
.then(data=>{ return data.json()})
.then(res=>{ console.log(res)})
}else{
fetch('http://localhost:3000/news',{
method:'POST',
headers:{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body:"id=jeff"
}).then(data=>{ return data.json()})
.then(res=>{ console.log(res)})
}
}
render(){
return (
<div className="App">
<User />
</div>
);
}
}
export default App;
node.js文件
var express=require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//创建服务器
var app=express();
//开启服务器并监听端口
app.listen(3000,function(){
console.log('this express server is running at http://127.0.0.1:3000 ');
})
app.get('/', function (req, res, next) {
});
app.get('/news', function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
var news = {
id: 1,
title: 'news title1...',
content: 'news content1...',
commentsUrl: '/comments?newsId='
};
res.json(news);
});
app.post('/news',urlencodedParser, function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
var id=req.body.id;
var news = {
id: id,
title: 'news title1...',
content: 'news content1...',
commentsUrl: '/comments?newsId='
};
res.json(news);
});
module.exports=app;
还没有评论,来说两句吧...