跨域CROS问题,由于浏览器同源策略访问限制,现IP与访问地址IP不同,都可以说成跨域。端口、协议、地址任意一种不同都算跨域。
解决跨域的办法有很多,后端解决主要在响应头中加入
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:可跨域的IP或者域名这两项内容。
这里主要记录SpringBoot项目后端全局配置解决方法。
当项目比较复杂,新建CrosConfig.java文件,代码如下:
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许发送Cookie
config.addAllowedOrigin("http://localhost:8081"); //
config.addAllowedHeader("*"); // 允许任何头
config.addAllowedMethod("*"); // 允许任何方法(GET, POST, PUT, DELETE等)
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config); // 对所有API生效
return new CorsFilter(source);
}
}
由于前端访问后端的端口不同,地址也不同,一直以为用devServer进行proxy代理就可以解决,最后发现地址重写不了,跨域也解决不了,参考了vue-admin-template这个模板,改了之后读取不到process.env中的变量值。
原来axios全局配置文件中读取proccess.env.变量值,变量需要是VUE_APP_变量名的格式才能读取到。
axios全局配置文件访问地址如下:
let http=axios.create({
baseURL: process.env.VUE_APP_BASE_API, //访问后端基本地址
timeout:5000
});
.env.development中的变量定义
```java
ENV = 'development'
#开发环境访问后端地址
VUE_APP_BASE_API = 'http://localhost:9097/demo/back'
vue.config.js配置
'use strict'
const path = require('path')
//const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = 'demo-back'
const port = 8081 //前端运行端口
module.exports = {
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: false,//关闭eslint检查
productionSourceMap: false,
devServer: {
port: port,
open: false,//关闭默认打开浏览器
overlay: {
warnings: false,
errors: true
},
}
}