springboot跨域請求設置,且允許js請求攜帶cookies


默認情況下由於瀏覽器的同源策略,對於來自於非同一站點的請求,會有一定的限時,

解決同源策略的限制一般情況下都是有以下幾種

1, jsonp方式,(遠古方案,實現麻煩,不推薦)

2,服務器代理方式,后端代理有nginx,,前端MVVM框架中的node.js (推薦,但如果沒有代理服務器的情況,為滿足此需求而加代理服務器,似乎不太現實)

3,filter過濾器方式,通過手動修改響應頭信息,及預檢信息實現(老項目中用的最多的一種)

4,直接使用springboot中集成的過濾器CorsFilter(以下將使用這一種)

 

springboot中開啟CORS非常簡單,僅需一個配置類,將CorsFilter注入到容器中即可

具體配置:

package com.abc.demoserver.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;

/**
 * @Auther:liangxh
 * @Date: 2020/05/06
 * @Description: CORS配置類
 */
@Configuration
public class CorsConfig {
    @Value("${cors.allowedHeaders}")
    private ArrayList allowedHeaders;   //消息頭設置
    @Value("${cors.allowedMethods}")
    private ArrayList allowedMethods;   //跨域方法允許設置
    @Value("${cors.allowedOrigins}")
    private ArrayList allowedOrigins;   //跨域請求源設置
    @Value("${cors.maxAge}")
    private Long maxAge;                //預檢有效期
    @Value("${cors.allowCredentials}")
    private Boolean allowCredentials;   //是否允許攜帶cookies
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(allowedHeaders);
        corsConfiguration.setAllowedOrigins(allowedOrigins);
        corsConfiguration.setAllowedMethods(allowedMethods);
        corsConfiguration.setAllowCredentials(allowCredentials);
        corsConfiguration.setMaxAge(maxAge);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

yml配置

#服務相關配置
server:
  port: 80
  servlet:
    context-path: /
#mybaits-plus相關配置
mybatis-plus:
  configuration:
    # 駝峰下划線轉換
    map-underscore-to-camel-case: true
    # 配置的緩存的全局開關
    cache-enabled: true
    # 延時加載的開關
    lazy-loading-enabled: true
    # 開啟的話,延時加載一個屬性時會加載該對象全部屬性,否則按需加載屬性
    multiple-result-sets-enabled: true
    use-generated-keys: true
    default-statement-timeout: 60
    default-fetch-size: 100
spring:
  profiles:
    active: dev
    #active: prod
  messages:
    basename: static/i18n/messages
    encoding: UTF-8
  http:
    encoding:
      charset: UTF-8
cors:
  allowCredentials: true
  allowedHeaders: x-requested-with, accept, origin, content-type
  allowedMethods: OPTIONS,HEAD,DELETE,GET,PUT,POST
  allowedOrigins: *
  maxAge: 3600

只需要以上簡單地配置即可,實現項目的跨域訪問

 

但是對於非常規情況下,js 在跨域訪問時是默認不攜帶的cookies的,某些場景如果我們需要js攜帶cookies,

這時我們需要設置兩個地方

1.后端過濾器中allowCredentials設置為true

2.前端還需開啟攜帶cookies配置 withCredentials:true

前端示例:

$.ajax({
  data:data,
  url:url,
  type:"POST",
  xhrFields:{
    withCredentials:true
  }

  success:function(res){
 ...
 }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM