因爲先後端不在一個端口上,也是屬於跨域問題的一種,因此必須解決這個問題.前端
react設置我這裏使用了fetch方式請求後端接口,因此在fentch方法裏設置兩個參數:java
直接上配置說吧
// An highlighted block @Configuration public class CorsConfig implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; String path = request.getServletPath(); //前端react項目的域名 response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); //設置容許訪問cookie response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); if (request.getMethod().equals("OPTIONS")) { response.setStatus(HttpServletResponse.SC_OK); }else{ chain.doFilter(request, res); } } @Override public void destroy() { } }
因爲一開始沒有設置關於請求OPTIONS的設置,致使個人put,delete請求都會發送2次請求到後端,而且報錯,說跨域問題,可是我這裏已經作了跨域配置,因此應該不是這個問題。react
if (request.getMethod().equals("OPTIONS")) { response.setStatus(HttpServletResponse.SC_OK); }else{ chain.doFilter(request, res); } }
後來翻閱了一些資料後,發現http請求,關於請求方法:get,post是基本請求,可是對於put,delete等其餘請求時,瀏覽器會先發送一個"PreFlight"請求,這個是一個預請求。因此,當發現是這種預請求的時候,後臺須要返回200的狀態。這樣配置完後,就ok了。spring