一、 先简单说明一下什么是跨域
浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域。
在前后端分离的模式下,前后端的域名是不一致的,此时就会发生跨域访问问题。在请求的过程中我们要想回去数据一般都是post/get请求,所以..跨域问题出现。
1.在同一台服务器中:
假设前端运行在:localhost:8010
假设后端运行在:localhost:8080
这里就是前端从8010 端口发送请求到后端的 8080 端口 ,这里就涉及到了端口不同造成的跨域问题
2.不在同一台服务器中:
假设前端运行在:123.1.23.101:8080
假设后端运行在: 127.0.0.1:8080
这里 就是前端从123.1.23.101:8080发送请求到后端的127.0.0.1:8080 ,这里就涉及到了域名不同造成的跨域问题
3.协议不同:
主要是http 与https 不同协议的见发送请求造成的
二、 如何解决跨域问题:
解决跨域问题主要是在Response 的请求头hear 上添加
ACCESS_CONTROL_ALLOW_ORIGIN
使得请求返回允许跨域
1.@CrossOrigin注解
@RequestMapping("/download")
@CrossOrigin
public void download(HttpServletRequest request, HttpServletResponse response) {
companyService.download(request,response);
}
通过添加 @CrossOrigin 注解 程序在底层运行时自动帮我在 Response 上添加了header 使得允许跨域访问
2.实现WebMvcConfigurer接口
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsCongif implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","POST")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
可以在改配置中配置允许跨域的url 和请求方法等,也可以通过maxAge设置记住对方的时间
3.手动设置HttpServletResponse
public class ResponseHeader {
public static void setResponseHeader(HttpServletResponse response, String fileName){
try {
response.reset();
response.setContentType("application/msexcel");
response.setCharacterEncoding("UTF-8");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName+".xlsx","UTF-8"))));
response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,"*");
response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,HttpHeaders.CONTENT_DISPOSITION);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
};
}
在返回前 使用 response 调用该方法实现手动添加header 实现允许跨域访问的设置,fileName 是博主导出指定文件名和类型使用的。