天天看点

react-proxy代理跨域

什么是跨域?

首先分析一个url:

http://www.exmple.com:3000/path/to/test.html?key1=value1&key2=value2#SomewhereInTheDocument

其中:

http://

属于协议,

www.example.com

属于域名,

:3000

属于端口,

/path/to/test.html

属于请求路径,

?key1=value1&key2=value2

属于请求参数,

#SomewhereInTheDocument

属于锚点。

只要协议、域名、端口三者中,有一个及以上不一致时,就属于跨域

如何用proxy代理解决跨域问题

首先安装http-proxy-middleware,在终端执行如下命令

npm install http-proxy-middleware

在项目的根目录下创建setupProxy.js文件,并在其中配置:

//引入需要用到的模块
const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
	// proxy第一个参数为要代理的路由
    app.use(createProxyMiddleware("/api1", {
        target: "https://www.baisu.com ",//配置你要请求的服务器地址,代理后的请求网址
        pathRewrite: {'^/api1': ''},//路径重写
        changeOrigin: true,//是否改变请求头
    })),

    app.use(createProxyMiddleware("/api2", {
        target: "https://sp0.baidu.com", //配置你要请求的服务器地址,代理后的请求网址
        pathRewrite: {'^/api2': ''}, //路径重写
        changeOrigin: true, // 是否改变请求头
    }))
    //如果有更多的url,也同理
};

           

最后只要在需要用到的地方把请求的服务器地址都替换成/api1就行了(以get为例)

axiox.get('/api1').then(res => {
      console.log(res);
   })
           

最后,记住一定要重新启动服务器,否则不会生效

继续阅读