react使用 http-proxy-middleware解決跨域問題


第一步 安裝 http-proxy-middleware

npm install http-proxy-middleware
順便安裝一下 axios ,不用也可以,用fetch也一樣。
npm install axios
  • 1
  • 2
  • 3

第二步 npm run eject 命令 配置暴露出來

npm run eject    
or
yarn eject
  • 1
  • 2
  • 3

第三步 src下創建一個 setupProxy.js文件

const proxy = require("http-proxy-middleware");
// console.log(1);
module.exports = function(app) {
  app.use(
    proxy("/api", {
      target: "http://m.kugou.com?json=true",
      changeOrigin: true
    })
  );
//   app.use(
//     proxy("/fans/**", {
//       target: "https://easy-mock.com/mock/5c0f31837214cf627b8d43f0/",
//       changeOrigin: true
//     })
//   );
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在這里插入圖片描述

第四步 start.js里面做一下配置

  require('../src/setupProxy')(devServer);
  • 1

在這里插入圖片描述

第五步 需要發送請求的地方 使用

 async componentDidMount(){
    let data = await axios.get('/api?json=true');
    let {data:{data:d,banner}} = data;

    let arr = [...banner,...banner];
    this.setState({
      iw:this.refs.banner.offsetWidth,
      arr,
      data:d
    });
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM