项目要做前后端分离,前端一律采用html使用ajax与后端交互,前端和后端是分开的项目,前端开发人员请求后台网址往往就要解决跨域的问题。现在模拟一下,说明如何解决这个问题,比如,http://localhost:8888/b.html,其代码如下:
<script src="jquery-1.12.4.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "http://localhost/backend/getGoodItems",
success: function(data){
console.log(data);
}
});
</script>
前端与后端端口不同,自然也是属于跨域的。
当访问"http://localhost:8888/b.html"时,b.html中的代码将会出现跨域调用,这样跨域访问的结果是:
Failed to load http://localhost/backend/getGoodItems: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.
jquery-1.12.4.min.js:4 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost/backend/getGoodItems with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
具体截图如下:
怎么解决呢?
在后端新建一个filter即可:
package com.roadjava.lzzcms.filter;
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.HttpServletResponse;
public class CrosFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res= (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
配置这个跨域处理的filter:
<filter>
<filter-name>CrosFilter</filter-name>
<filter-class>com.zhongan.loansupermarket.filter.CrosFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CrosFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
就这样就可以了,再次请求"http://localhost:8888/b.html",请求成功了: