springboot2.0專案axios跨域options請求攜帶自定義header後臺接收不到
阿新 • • 發佈:2019-01-01
前臺發起請求後報錯
Failed to load http://192.168.1.107:8066/talk/queryList: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'http://192.168.1.107:8080' is therefore not allowed access.
參考了兩個文章:
https://www.2cto.com/kf/201711/700228.html
https://www.jianshu.com/p/f37f8c295057
解決辦法是:
配置類
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { //設定允許跨域的路徑 registry.addMapping("/**") //設定允許跨域請求的域名 .allowedOrigins("*") //是否允許證書 不再預設開啟 .allowCredentials(true) //設定允許的方法 .allowedMethods("*") .allowedHeaders("*") //跨域允許時間 .maxAge(3600); } }
過濾器裡面設定下:
if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
chain.doFilter(request, response);
}
如果是options請求則不進行那些校驗,
因為我這裡options請求無法攜帶頭請求,但具體是不是所有的options都無法攜帶頭請求我也不知道,別人告訴我說因為這個options自動生成的所以沒有攜帶頭請求,如果自己生成的可以攜帶
package com.qky.qingchi.config; import com.qky.qingchi.util.CookieUtils; import com.qky.qingchi.util.TokenUtils; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @Configuration @WebFilter(filterName = "myFilter", urlPatterns = "/*") public class MyFilter implements Filter { @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if (req.getMethod().equals(RequestMethod.OPTIONS.name())) { chain.doFilter(request, response); } String cookieToken = CookieUtils.getCookie(req, "token"); String headerToken = req.getHeader("token"); System.out.println("headerToken27:" + headerToken); if (TokenUtils.notCorrect(headerToken) && !req.getRequestURI().contains("login")) { return; } chain.doFilter(request, response); } @Override public void destroy() { } }
之前我沒有加
if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
chain.doFilter(request, response);
}
這行程式碼,所有請求都去獲取token,然後options請求是獲取不到header裡面的token的,所以會報錯,