springmvc跨域問題

一、跨域問題:

按照網上全部的方法試了一遍,都沒跨過去,正在無助之際,使用filter按照下面的方法解決的時候出現了起色:java

添加filter:web

package com.thc.bpm.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletRequest request = (HttpServletRequest)servletRequest; String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Authentication"); response.setHeader("Access-Control-Allow-Credentials", "true"); String method = request.getMethod(); if(method.equalsIgnoreCase("OPTIONS")){ servletResponse.getOutputStream().write("Success".getBytes("utf-8")); }else{ filterChain.doFilter(servletRequest, servletResponse); } } @Override public void destroy() { } }

在web.xml配置田間上面的過濾器:apache

<filter> <filter-name>corsFilter</filter-name> <filter-class>com.thc.bpm.filter.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>corsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

image

測試的時候發現報錯不同了:
image
主要是這句話:Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response
大體翻譯下意思是:請求頭中有個字段「x-access-token」,這個字段不被預運行響應中的Access-Control-Allow-Headers所容許。
我突然想到咱們的token就是放在x-access-token這個字段中,而過濾器中相關設置爲:跨域

response.setHeader("Access-Control-Allow-Headers", "Authentication");

那就把Authentication換成x-access-token試試:瀏覽器

response.setHeader("Access-Control-Allow-Headers", "x-access-token");

image
再測試一次:緩存

image

二、總結cors常見的header:

Access-Control-Allow-Origin: http://foo.org
Access-Control-Max-Age: 3628800
Access-Control-Allow-Methods: GET,PUT, DELETE
Access-Control-Allow-Headers: content-typeapp

"Access-Control-Allow-Origin"代表它容許"http://foo.org"發起跨域請求;
"Access-Control-Max-Age"代表在3628800秒內,不須要再發送預檢驗請求,能夠緩存該結果;
"Access-Control-Allow-Methods"代表它容許GET、PUT、DELETE的外域請求;
"Access-Control-Allow-Headers"代表它容許跨域請求包含content-type頭;cors

預檢請求用的方法是OPTIONS,表示這個請求是用來詢問的。關鍵字段是Origin,表示請求來自哪一個源。
除了Origin以外,還有兩個特殊字段:
Access-Control-Request-Method:該字段是必須的,用來列出CORS請求會用到那些方法。
Access-Control-Request-Headers:該字段是一個逗號分隔的字符串,指定瀏覽器CORS請求會額外發送的頭信息字段。ide

相關文章
相關標籤/搜索