复制代码
1
2
3
41、通过node.js搭建服务器,且必须有跨域请求 2、php搭建的不行,估计是跨域的问题 3、在页面渲染后的componentDidMount()生命周期函数中发送请求
代码示例:
react.js文件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47import 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文件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53var 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;
最后
以上就是忧虑银耳汤最近收集整理的关于react 处理fetch网络请求的全部内容,更多相关react内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复