zoukankan      html  css  js  c++  java
  • 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

    在这里插入图片描述

  • 相关阅读:
    router使用以及vue的动画效果
    配置wbepack
    Axios插件和loading的实现
    自定义组件的 v-model
    组件模块化使用
    组件基础
    vue的使用1
    solt插槽的使用。
    Vue的使用
    Vue的router使用
  • 原文地址:https://www.cnblogs.com/ljh12138/p/13559364.html
Copyright © 2011-2022 走看看