1、spring boot跨域配置有两种方法
在后端使用spring boot。spring boot跨域非常简单,只需书写以下代码即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@configuration
public class customcorsconfiguration {
private corsconfiguration buildconfig() {
corsconfiguration corsconfiguration = new corsconfiguration();
corsconfiguration.addallowedorigin( "*" );
corsconfiguration.addallowedheader( "*" );
corsconfiguration.addallowedmethod( "*" );
corsconfiguration.setallowcredentials( true );
return corsconfiguration;
}
@bean
public corsfilter corsfilter() {
urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
source.registercorsconfiguration( "/**" , buildconfig());
return new corsfilter(source);
}
}
|
2.nginx跨域配置
spring boot应用用nginx反向代理。而前端跨域请求的需求不减。
nginx跨域也比较简单,只需添加以下配置即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
location / {
proxy_pass http: //localhost:8080;
if ($request_method = 'options' ) {
add_header 'access-control-allow-origin' '*' ;
add_header 'access-control-allow-methods' 'get, post, options' ;
add_header 'access-control-allow-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token' ;
add_header 'access-control-max-age' 1728000 ;
add_header 'content-type' 'text/plain; charset=utf-8' ;
add_header 'content-length' 0 ;
return 204 ;
}
if ($request_method = 'post' ) {
add_header 'access-control-allow-origin' '*' ;
add_header 'access-control-allow-methods' 'get, post, options' ;
add_header 'access-control-allow-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token' ;
add_header 'access-control-expose-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token' ;
}
if ($request_method = 'get' ) {
add_header 'access-control-allow-origin' '*' ;
add_header 'access-control-allow-methods' 'get, post, options' ;
add_header 'access-control-allow-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token' ;
add_header 'access-control-expose-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token' ;
}
}
|
其中:add_header 'access-control-expose-headers' 务必加上你请求时所带的header。
例如本例中的“token”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。
三、浏览器设置跨域
chrome、firefox本身是可以通过配置支持跨域请求的。
chrome跨域:参考文档:chrome跨域
四、前端vue设置跨域
先设置 axios
1
2
3
4
5
6
|
axios.defaults.withcredentials = true ;
axios.defaults.headers.common[ 'x-requested-with' ] = 'xmlhttprequest' ; //证明是ajax 请求
psot 请求加入
headers: {
'content-type' : 'application/x-www-form-urlencoded; charset=utf-8' ,
}
|
设置config 文件下面的index.js 然后就可以再其它页面访问了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/sky786905664/article/details/79189378