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