文章目录
1.配置类方式(实现WebMvcConfigurer)
2.使用@CrossOrigin注解
3.使用nginx反向代理解决跨域
4.Vue中配置代理服务器
方式一(案例1)
- 配置vue.config.js
- 注意5000代表请求后端的端口
module.exports = {
//开启代理服务器
devServer: {
proxy: 'http://localhost:5000',
}
}
更改请求端口为本机端口
- 8080表示前端端口,保持端口对应即可
问题解决
重启服务器,重启脚手架
思维图
Vue代理缺点
- 不能控制是否需要代理
- 只能代理一个服务器
方式一(案例2)
我们请求一个http://localhost:9000/demo/user/list地址
- 请求代码
getUserList() {
axios({
method: 'get',
url: 'http://localhost:8080/demo/user/list',
})
.then(res => {
console.log(res)
this.tableData = res.data
})
- vue.config.js代码
devServer: {
proxy: 'http://localhost:9000',
},
方式二(案例1)
初始原始
devServer: {
proxy: {
//请求前缀
'api': {
target: '',
ws: true, //用于支持websocket
changeOrigin: true, //用于控制请求头中的host值,默认是true
},
'/foo': {
target: '<other_url>',
},
},
},
开启代理
devServer: {
proxy: {
//请求前缀
'/atguigu': {
target: 'http://localhost:5000',
},
},
},
- 加上前缀
注意
- 让目标服务器规避这个请求头
pathRewrite: { '^/atguigu': '' },
devServer: {
proxy: {
//请求前缀
'/atguigu': {
target: 'http://localhost:5000',
pathRewrite: { '^/atguigu': '' },
},
},
},
其他功能介绍
ws: true, //用于支持websocket
changeOrigin: true, //用于控制请求头中的host值,默认是true
开启多个代理
devServer: {
proxy: {
//请求前缀
'/atguigu': {
target: 'http://localhost:5000',
pathRewrite: { '^/atguigu': '' },
ws: true, //用于支持websocket
changeOrigin: true, //用于控制请求头中的host值,默认是true
},
// '/foo': {
// target: '<other_url>',
// },
'/demo': {
target: 'http://localhost:5001',
pathRewrite: { '^/demo': '' },
ws: true, //用于支持websocket
changeOrigin: true, //用于控制请求头中的host值,默认是true
},
},
},
方式二(案例2)
- 依然是请求http://localhost:9000/demo/user/list
getUserList() {
axios({
method: 'get',
url: '/abc/demo/user/list',
})
.then(res => {
console.log(res)
this.tableData = res.data
})
//开启代理服务器
devServer: {
proxy: {
'/abc': {
target: 'http://localhost:9000',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/abc' : ''
}
}
}
},