引言
什么是跨域
跨域问题一般出现在网站的js代码里面,原因是引用了非本域名下的资源,或者ajax请求发送到非本域名的目标地址。
什么情况会出现跨域
比如协议、ip、端口等不一致都会出现跨域的情况
本地开发解决方案
vue配置文件解决跨域
在vue.config.js文件中修改配置
module.exports = defineConfig({
publicPath: './',
runtimeCompiler: true,
devServer:{
port:8080, //设置端口号
proxy:{
'/api':{
target:"http://localhost:9090",
changOrigin: true, //允许跨域
pathRewrite:{
'^/api':'' //重写路径
}
}
}
}
})
修改axios请求路径
const request = axios.create({
// baseURL: 'http://localhost:9090', 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
baseURL: `http://localhost:8080/api`,
timeout: 5000,
})
解释:
当我们在访问的网页中带有http://localhost:8080/api路径的网页,vue就会将http://localhost:8080/api代理到http://localhost:9090主机上
java 后端解决跨域
将CorsFilter注入到sping容器中。
@Configuration
public class CorsCofig {
//当前跨域请求最大有效时长,这里默认1天
private static final long MAX_AGE=24*60*60;
@Bean
public CorsFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //设置访问源地址
corsConfiguration.addAllowedHeader("*"); //设置访问源请求头
corsConfiguration.addAllowedMethod("*"); //设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**",corsConfiguration); //对接口配置跨域设置
return new CorsFilter(source);
}
}
使用nginx解决跨域
将vue.config.js文件devServer注释,在使用npm run build命令对vue进行打包构建
module.exports = defineConfig({
publicPath: './',
runtimeCompiler: true,
// devServer:{
// port:8080, //设置端口号
// proxy:{
// '/api':{
// target:"http://localhost:9090",
// changOrigin: true, //允许跨域
// pathRewrite:{
// '^/api':'' //重写路径
// }
// }
// }
// }
})
修改axios请求的ip地址,不能写localhost
const request = axios.create({
// baseURL: 'http://localhost:9090', 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
baseURL: `http://${dnsIp}:80/api`,
timeout: 5000,
})
配置nginx的nginx.conf文件
server { #表示一台主机
listen 80; #访问的端口号
server_name nginx01.com;#访问的域名或者主机名,可以使用多个用逗号隔开,也可以使用正则匹配多个
location / {
root /opt/apps/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://127.0.0.1:9090/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
注意点:
后端代码打包的时候,必须将CorsFilter注入到sping容器中,否则可能出现各种各样的问题