react配置代理避免跨域
方法一、package.json中写
此处为服务器端地址
"proxy":"http://127.0.0.1:9527/"
此处为客户端地址,http://localhost:3000/info->走代理->服务器()
axios.get('http://localhost:3000/info').then((res) => {
console.log(res.data)
})
方法二、在src文件夹下新建setupProxy.js文件
//代码会交给webpack执行属于后端代码,使用require引入
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
proxy('/api1', {//遇见/api1前缀的请求,触发代理
target: 'http://127.0.0.1:9527/',//请求转发给谁
changeOrigin: true,//控制服务器收到请求头中的Host,如果是false收到的就是真是客户端地址localhost:3000,是true就是127.0.0.1:9528
pathRewrite: {
'/api1': ''//重新请求路径
}
}),
proxy('/api2', {
target: 'http://127.0.0.1:9528/',
changeOrigin: true,
pathRewrite: {
'/api2': ''
}
})
)
}
getInfo = () => {
console.log(123)
axios.get('http://localhost:3000/api1/info').then((res) => {
console.log(res.data)
})
}
getData = () => {
console.log(123)
axios.get('http://localhost:3000/api2/info').then((res) => {
console.log(res.data)
})
}
vue配置代理避免跨域
在vue.config.js中写,原理与上述二相同
module.exports = {
devServer: {
proxy: {
'/api1': {//遇见/api1前缀的请求,触发代理
target: 'http://127.0.0.1:9527',//请求转发给谁
changeOrigin: true,//控制服务器收到请求头中的Host,如果是false收到的就是真是客户端地址localhost:3000,是true就是127.0.0.1:9528
pathRewrite: {
'/api1': ''//重新请求路径
}
}
},
},
}