react 跨域配置(proxy——单向跨域代理配置、http-proxy-middleware——接口转发器)
一、单向跨域代理(所有请求发向于同一个http地址)
在package.json文件中使用proxy配置可以解决单向跨域问题
"proxy":{
"/api":{
"target":"http://m.kugo.com",
"changeOrigin": true
,
"pathRewrite": {
'^/api': '',
},
}
}
“/api”(在项目有请求地址带/api的都会被代理到target路径下)
“target”(用于设置代理请求的地址)
“changeOrigin”(请求头,changeOrigin默认是false:请求头中host仍然是浏览器发送过来的host,如果设置成true:发送请求头中host会设置成target
)
“pathRewrite”(重写路径,比如我们请求的路径是:http://localhost:3000/api/user-info,最终发出去的请求路径是:http://localhost:3000/user/user-info)
二、多个不同跨域地址请求(每个跨域请求地址都不一样,稍微复杂一点的跨域请求都推荐使用这个)
npm i --save-dev http-proxy-middleware
新建一个setupProxy.js(用于存放所有的跨域请求代理配置,setupProxy可以换成自己喜欢的名字)
setupProxy.js里代码如下
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(proxy('/index', {
target: "https://suggest.taobao.com ",
changeOrigin: true,
pathRewrite: {
'^/index': '',
},
onProxyReq(proxyReq, req, res) {
proxyReq.setHeader('cookie', 'SERVER_TOKEN=153b8baf-4b2d');
}
})
);
app.use(proxy('/add', {
target: " https://api.cdnjs.com/ ",
changeOrigin: true,
pathRewrite: {
'^/add': '',
},
})
);
};
“/api”(在项目有请求地址带/api的都会被代理到target路径下)
“target”(用于设置代理请求的地址)
“changeOrigin”(请求头,changeOrigin默认是false:请求头中host仍然是浏览器发送过来的host,如果设置成true:发送请求头中host会设置成target
)
“pathRewrite”(重写路径,比如我们请求的路径是:http://localhost:3000/api/user-info,最终发出去的请求路径是:http://localhost:3000/user/user-info)
“onProxyReq”(onProxyReq(),非常重要,我们服务器通常会通过cookie或者token来验证用户身份,那我们就可以通过代理时给请求头加入相应的信息,这样就可以通过服务器的身份验证了)
三、项目请求示例
axios({
url: '/index/sug',
params: {
"code": "utf-8",
"q": "玩具"
}
}).then((res)=>{
console.log(res)
})
/index是上面进行了代理的地址