一、現象
從fetch說起,用fetch構造一個POST請求。
1 fetch('http://127.0.0.1:8000/api/login', { 2 method: "POST", 3 headers: ({ 4 'Content-Type': 'application/x-www-form-urlencoded' 5 }), 6 body: "name=" + name + "&password=" + pwd 7 }).then((res) = >{ 8 console.log(res.status); 9 return res.json() 10 }).then((data) = >{ 11 // console.log(data.result) 12 let loginResult = data.result 13 if (loginResult == 'ok') { 14 dispatch(getSuccess(data.list)) browserHistory.push('/index') 15 } else { 16 console.log("illegal login in !") 17 } 18 }). 19 catch((e) = >{ 20 console.log(e.message) 21 })
調用的API服務是Spring boot開發的。
這個POST發出去,一切正常。
由於業務需要,我增加一個頭字段:Authorization。
fetch請求的代碼修改如下:
1 ... 2 3 headers: ({ 4 'Content-Type': 'application/x-www-form-urlencoded', 5 'Authorization': '1111111222' 6 }), 7 body: "name=" + name + "&password=" + pwd 8 }).then((res) = >{ 9 10 ...
問題出現了,服務器收到一個OPTIONS請求?!
二、原因
這是fetch出於安全性考慮做的一次服務器預查詢,而我的服務沒有做相應的處理,所以業務處理失敗了。
三、解決
方法一:
網上查到的最多的說法就是:
在application.properties文件中增加這一行配置:
spring.mvc.dispatch-options-request=true
遺憾的是,我的環境配置沒有生效。
方法二:
手動寫一個Filter:
0 @Component
1 public class CorsFilter implements Filter { 2 @Override 3 public void init(FilterConfig filterConfig) throws ServletException { 4 // TODO Auto-generated method stub 5 } 6 7 @Override 8 public void doFilter(ServletRequest req, ServletResponse res, 9 FilterChain chain) throws IOException, ServletException { 10 HttpServletResponse response = (HttpServletResponse) res; 11 response.setHeader("Access-Control-Allow-Origin", "*"); 12 response.setHeader("Access-Control-Allow-Methods", 13 "POST, GET, OPTIONS, DELETE"); 14 response.setHeader("Access-Control-Max-Age", "3600"); 15 response.setHeader("Access-Control-Allow-Headers", 16 "Content-Type, x-requested-with, X-Custom-Header, Authorization"); 17 chain.doFilter(req, res); 18 } 19 20 @Override 21 public void destroy() { 22 // TODO Auto-generated method stub 23 } 24 }
一點說明:
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization");
配置中的Authorization是和請求中自定義的頭部字段是一樣的。
通過這個過濾器,fetch后續的POST請求就可以順利的發出了。