spring boot配合前端實(shí)現(xiàn)跨域請(qǐng)求訪問
一.方法:
- 服務(wù)端設(shè)置Respone Header頭中Access-Control-Allow-Origin
- 配合前臺(tái)使用jsonp
- 繼承WebMvcConfigurerAdapter 添加配置類
二.實(shí)例:
1.前端:因?yàn)槲覀冇昧饲昂蠖朔蛛x,前端用node服務(wù)器,node服務(wù)器再用了ajax反向代理請(qǐng)求到我的spring boot 服務(wù)器。其中node服務(wù)器也用了ajax發(fā)出請(qǐng)求所以也存在跨域的問題。具體代碼:
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; } }));
后臺(tái)(用的是spring boot 1.3.7.RELEASE) :用了一個(gè)filter進(jìn)行了身份驗(yàn)證同時(shí)進(jìn)行了跨域處理,具體代碼:
public class AuthFilter implements Filter { // @Autowired //這個(gè)不能自動(dòng)注入servlet和filter是被tomcat管理的 private BaseUserService baseUserService; private String[] excludePaths; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("initFilter"); //不能在初始化中通過Appliaction Context獲取因?yàn)檫@時(shí)候還沒初始化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; //這里填寫你允許進(jìn)行跨域的主機(jī)ip httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); //允許的訪問方法 httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH"); //Access-Control-Max-Age 用于 CORS 相關(guān)配置的緩存 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動(dòng)作之前加上這句話,也就是在代碼的最前面加上這個(gè)話。
跨域資源共享 CORS 詳解(相關(guān)鏈接)
2.詳細(xì)請(qǐng)看(點(diǎn)開)
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); } }
這里有個(gè)坑spring boot 以前的版本這樣設(shè)置可以用但是 我用的1.3.7.RELEASE spring boot 不能用,所以用第二種方式是萬(wàn)能的
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot解決跨域請(qǐng)求攔截問題代碼實(shí)例
- Springboot解決ajax+自定義headers的跨域請(qǐng)求問題
- 詳解Spring Boot 2.0.2+Ajax解決跨域請(qǐng)求的問題
- 詳解springboot設(shè)置cors跨域請(qǐng)求的兩種方式
- vue+springboot實(shí)現(xiàn)項(xiàng)目的CORS跨域請(qǐng)求
- Spring Boot Web應(yīng)用開發(fā) CORS 跨域請(qǐng)求支持
- 詳解SpringBoot多跨域請(qǐng)求的支持(JSONP)
- Spring Boot設(shè)置支持跨域請(qǐng)求過程詳解
相關(guān)文章
使用Spring-Retry解決Spring Boot應(yīng)用程序中的重試問題
重試的使用場(chǎng)景比較多,比如調(diào)用遠(yuǎn)程服務(wù)時(shí),由于網(wǎng)絡(luò)或者服務(wù)端響應(yīng)慢導(dǎo)致調(diào)用超時(shí),此時(shí)可以多重試幾次。用定時(shí)任務(wù)也可以實(shí)現(xiàn)重試的效果,但比較麻煩,用Spring Retry的話一個(gè)注解搞定所有,感興趣的可以了解一下2023-04-04詳解如何使用Jersey客戶端請(qǐng)求Spring Boot(RESTFul)服務(wù)
本篇文章主要介紹了詳解如何使用Jersey客戶端請(qǐng)求Spring Boot(RESTFul)服務(wù),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01Java?多個(gè)文件生成zip包、下載zip包的實(shí)現(xiàn)代碼
這篇文章主要介紹了Java?多個(gè)文件生成zip包、下載zip包,包括文件上傳,文件下載,多個(gè)文件打成zip包的操作代碼,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01解決spring AOP中自身方法調(diào)用無法應(yīng)用代理的問題
這篇文章主要介紹了解決spring AOP中自身方法調(diào)用無法應(yīng)用代理的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08SpringBoot淺析緩存機(jī)制之Ehcache?2.x應(yīng)用
EhCache?是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有快速、精干等特點(diǎn)。它是Hibernate中的默認(rèn)緩存框架。Ehcache已經(jīng)發(fā)布了3.1版本。但是本文的講解基于2.x版本2022-08-08