跨域问题
现在开发比较流行前后端分离的方式,可是前后端分离的环境下,前端与后端在不同的端口启动,前端在调用后端的时候由于安全等因素是不被允许的,这事我们就需要跨域。
跨域问题的解决,其实前后端都是可以处理的,不过我们作为后端开发人员就来谈谈后端的跨域问题。
springBoot解决跨域问题
在springBoot项目中我们首先要在spring可以扫描到的包下创建个类用于配置跨域问题的参数:
package com.imooc.config;
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;
@Configuration
public class CorsConfig {
public CorsConfig(){
}
@Bean
public CorsFilter corsFilter(){
// 1. 添加cors配置信息
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:8080"); //设置允许跨域的地址
//设置是否发送cookie信息
config.setAllowCredentials(true);
//设置允许请求的方式 get post 等等
config.addAllowedMethod("*");
// 设置允许的header
config.addAllowedHeader("*");
// 2. 为url添加映射路径 --可以映射的url 要用org.springframework.web.cors包下的
UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
corsSource.registerCorsConfiguration("/**", config);
// 3. 返回定义好的corsSource
return new CorsFilter(corsSource);
}
}
这里 CorsFilter 对象要是用org.springframework.web.filter包下的。并且在类的方法上要加上@Bean注解表示这是个bean。