react 配置代理 解决跨域

/*
跨域 
1、 jsonp 最原始
2、 CORS 后台解决跨域方法 Access-Control-Allow-Origin
3、前端配置代理   在本地装一个node -> 后台接口 我们的ajax -> node服务 本地开发才有, 打包上线 就没有node了 
 
*/

官网:https://www.html.cn/create-react-app/docs/proxying-api-requests-in-development/

第一步:

$ npm install http-proxy-middleware --save
$ # 或
$ yarn add http-proxy-middleware

  

第二步:创建 src/setupProxy.js 并将以下内容放入该文件中:

const proxy  = require('http-proxy-middleware')

module.exports = function (app) {
  app.use(
    proxy('/api', {
      target: 'http://localhost:3000/',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    }),
  )
}

  

结尾: 如果配置多个代理。复制一份 app.use(),然后把上面哪个'api‘名字换了。把target路径换了就可以了。

猜你喜欢

转载自www.cnblogs.com/yetiezhu/p/12740708.html