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){ ... } })
本文来自博客园,作者:夜半风起,转载请注明原文链接:https://www.cnblogs.com/yebanfengqi/p/12875365.html