跨域问题的解决方法及不成功的多种原因
跨域问题的解决方法
在前后端分离式开发的项目中,常出现跨域问题,不同端口或者不同IP开发的前后端项目均会出现;
常见报错状态码:
- 403 Forbidden
开发环境可用在vue.config.js设置代理,生产环境采用ngnix解决
vue.config.js
module.exports = {
......
devServer: {
// development server port 8000
port: 8002,
disableHostCheck: true,
proxy: {
// 跨域目标的URL
'/api': {
target: 'http://x:x:x:x:8000',
pathRewrite: { '^/api': '' },
ws: false,
changeOrigin: true,
},
},
},
}
跨域不成功的多种原因
1. 少了一个/api
如果后端接口为:http://127:0:0:1:8000/api/getData/xx,而刚好代理设置为/api
注意跨域设置需为:
module.exports = {
......
// 跨域目标的URL
'/api': {
target: 'http://x:x:x:x:8000',
pathRewrite: { '^/api': '/api' }, // {'^/': '' } 或者干脆不写pathRewrite
ws: false,
changeOrigin: true,
},
}
注:‘^/api’: ‘/api’ 或者 '^/ ': ’ ’ 而非 ‘^/api’: ’ ’
2. 后端配置跨域
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}