react 处理fetch网络请求

今天药忘吃喽~ 2021-07-24 22:03 501阅读 0赞
  1. 1、通过node.js搭建服务器,且必须有跨域请求
  2. 2php搭建的不行,估计是跨域的问题
  3. 3、在页面渲染后的componentDidMount()生命周期函数中发送请求

代码示例:

react.js文件

  1. import React ,{ Component}from 'react';
  2. import User from './user'
  3. class App extends React.Component {
  4. constructor()
  5. {
  6. super();
  7. }
  8. componentDidMount()
  9. {
  10. var flag=false;
  11. if(flag)
  12. {
  13. fetch('http://localhost:3000/news')
  14. .then(data=>{ return data.json()})
  15. .then(res=>{ console.log(res)})
  16. }else{
  17. fetch('http://localhost:3000/news',{
  18. method:'POST',
  19. headers:{
  20. 'Accept': 'application/json, text/plain, */*',
  21. 'Content-Type': 'application/x-www-form-urlencoded'
  22. },
  23. body:"id=jeff"
  24. }).then(data=>{ return data.json()})
  25. .then(res=>{ console.log(res)})
  26. }
  27. }
  28. render(){
  29. return (
  30. <div className="App">
  31. <User />
  32. </div>
  33. );
  34. }
  35. }
  36. export default App;

node.js文件

  1. var express=require('express');
  2. var bodyParser = require('body-parser');
  3. var app = express();
  4. var urlencodedParser = bodyParser.urlencoded({ extended: false });
  5. //创建服务器
  6. var app=express();
  7. //开启服务器并监听端口
  8. app.listen(3000,function(){
  9. console.log('this express server is running at http://127.0.0.1:3000 ');
  10. })
  11. app.get('/', function (req, res, next) {
  12. });
  13. app.get('/news', function (req, res, next) {
  14. res.set('Access-Control-Allow-Origin', '*');
  15. var news = {
  16. id: 1,
  17. title: 'news title1...',
  18. content: 'news content1...',
  19. commentsUrl: '/comments?newsId='
  20. };
  21. res.json(news);
  22. });
  23. app.post('/news',urlencodedParser, function (req, res, next) {
  24. res.set('Access-Control-Allow-Origin', '*');
  25. var id=req.body.id;
  26. var news = {
  27. id: id,
  28. title: 'news title1...',
  29. content: 'news content1...',
  30. commentsUrl: '/comments?newsId='
  31. };
  32. res.json(news);
  33. });
  34. module.exports=app;

发表评论

表情:
评论列表 (有 0 条评论,501人围观)

还没有评论,来说两句吧...

相关阅读