您好,登錄后才能下訂單哦!
一.方法:
二.實例:
1.前端:因為我們用了前后端分離,前端用node服務器,node服務器再用了ajax反向代理請求到我的spring boot 服務器。其中node服務器也用了ajax發出請求所以也存在跨域的問題。具體代碼:
app.all(apiRoot + '/*', proxy('127.0.0.1:' + proxyPort, { forwardPath: function(req, res) { console.log('req: ', req, 'res; ', res); return require('url').parse(req.url).path; } }));
后臺(用的是spring boot 1.3.7.RELEASE) :用了一個filter進行了身份驗證同時進行了跨域處理,具體代碼:
public class AuthFilter implements Filter { // @Autowired //這個不能自動注入servlet和filter是被tomcat管理的 private BaseUserService baseUserService; private String[] excludePaths; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("initFilter"); //不能在初始化中通過Appliaction Context獲取因為這時候還沒初始化Application Context //baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class); excludePaths = new String[]{"/api/user/noLogin", "/api/user/tokenError", "/api/user/loginForeground", "/api/user/loginBackground", "/api/user/inCorrectUserId"}; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; //這里填寫你允許進行跨域的主機ip httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); //允許的訪問方法 httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH"); //Access-Control-Max-Age 用于 CORS 相關配置的緩存 httpServletResponse.setHeader("Access-Control-Max-Age", "3600"); httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); String userId = request.getParameter("userId"); String token = request.getParameter("token"); //有token的 ` if (userId != null && token != null) { try { Integer id = Integer.parseInt(userId); if (baseUserService == null) baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class); int status = baseUserService.checkLogin(id, token); if (status == 1) { chain.doFilter(request, response); } else if (status == 0) { httpServletResponse.sendRedirect("/api/user/tokenError"); } else if (status == -2) { httpServletResponse.sendRedirect("/api/user/inCorrectUserId"); } else { httpServletResponse.sendRedirect("/api/user/noLogin"); } } catch (NumberFormatException exception) { httpServletResponse.sendRedirect("/api/user/inCorrectUserId"); } } else { String path = httpServletRequest.getServletPath(); if (excludePath(path)) { chain.doFilter(request, response); } else { httpServletRequest.getRequestDispatcher("/api/user/noLogin").forward(request, response); } } // ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*"); // CorsFilter corsFilter=new CorsFilter(); } private boolean excludePath(String path) { for (int i = 0; i < excludePaths.length; i++) { if (path.equals(excludePaths[i])) return true; } return false; } @Override public void destroy() { System.out.println("destroy method"); } }
這種方法還適用于servlet中,特別注意的是一定要在filter動作之前加上這句話,也就是在代碼的最前面加上這個話。
跨域資源共享 CORS 詳解(相關鏈接)
2.詳細請看(點開)
3.具體代碼:
package edu.ecnu.yjsy.conf; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CorsConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600); } }
這里有個坑spring boot 以前的版本這樣設置可以用但是 我用的1.3.7.RELEASE spring boot 不能用,所以用第二種方式是萬能的
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。