SpringBoot跨域请求
程序员文章站
2022-07-10 11:17:03
...
在软件开发过程中,尤其是现在的前后端分离开发,跨域请求是很普通的事情,我这个只是简单的将所有的跨域请求都接受,如若有大佬有更好的解决方案欢迎分享
问题:
在请求的时候,前端使用js进行ajax请求未能接收到预期的数据,却得到了一个跨域请求的报错。
解决办法
项目是使用SpringBoot构建的,在项目中添加一个过滤器AjaxFilter,使用这个过滤器对所有的请求进行处理。
主要是添加请求头
代码
-
AjaxFilter 访问请求过滤器
package com.chen.dataserver.filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by handsome programmer. * User: chen * Date: 2018/5/27 * Time: 17:36 * Description: 跨域拦截器,解决跨域问题3 */ @WebFilter(filterName = "ajaxFilter", urlPatterns = {"/*"}) public class AjaxFilter implements Filter { private static Logger logger = LoggerFactory.getLogger(AjaxFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletRequest request = (HttpServletRequest) servletRequest; String requestURI = request.getRequestURI(); logger.info("过滤到的请求--->" + requestURI); // 指定允许其他域名访问 response.setHeader("Access-Control-Allow-Origin", "*"); // 响应类型 response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE"); // 响应头设置 response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
在项目启动的入口类上面即Application上面添加@ServletComponentScan注解。
测试代码
<!DOCTYPE html>
<html lang="zh" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<script type="text/javascript">
// 创建XMLHttpRequest对象
var xmlHttpRequest;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlHttpRequest = new XMLHttpRequest();
} else {
// IE6, IE5 浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.open("GET", "http://localhost:8080/pc/getRecordsFromStaticNode", true);
xmlHttpRequest.send();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
console.log(xmlHttpRequest.responseText);
}
}
</script>
</head>
<body>
</body>
</html>