如何简单有效而彻底实现跨域访问

tech2024-06-18  68

在一次接口开发过程中,前端同事访问了我的接口:user/getUserInfo.html,前端的代码是加载在localhost:8080服务上的,访问远程这个接口的时候出现跨域问题,中间查询了很多资料,终极版本的解决方案如下:

import org.springframework.web.bind.annotation.CrossOrigin; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 跨域访问 * * @author lh * @version 1.0 * @date 2020-09-03 11:53 */ public class CrossOriginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse resp = (HttpServletResponse) response; HttpServletRequest req = (HttpServletRequest) request; String type = req.getMethod(); resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); resp.setHeader("Access-Control-Max-Age", "3600"); resp.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, Accept, Origin"); resp.setHeader("Access-Control-Allow-Credentials", "true"); if (type.toUpperCase().equals("OPTIONS") == true) { resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setHeader("Access-Control-Allow-Headers", "content-type"); resp.setContentType("text/plain;charset=utf-8"); } chain.doFilter(req, resp); } @Override public void destroy() { } }

解释:

resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); resp.setHeader("Access-Control-Max-Age", "3600"); resp.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, Accept, Origin"); resp.setHeader("Access-Control-Allow-Credentials", "true");

这几个配置是为了配置除开ContentType:"application/json"这种方式的跨域访问。

if (type.toUpperCase().equals("OPTIONS") == true) { resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setHeader("Access-Control-Allow-Headers", "content-type"); resp.setContentType("text/plain;charset=utf-8"); }

这几个代码主要是给ContentType:"application/json"这种方式的跨域访问。因为第一次会发起OPTIONS请求,OPTIONS成功后才会发起第二次请求,所以这种需要特殊处理一下。

以上得代码是经历了真实实践,最后也解决了问题。

 

最新回复(0)