1. 程式人生 > >fetch跨域請求 + spring mv 跨域支援

fetch跨域請求 + spring mv 跨域支援

JS發起請求:
fetch(url, {
  method: 'POST',
  body: 'p1=v1&p2=v2',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  credentials: 'same-origin',
  mode: 'cors'
})
    credentials
  • omit: 預設值,忽略cookie的傳送

  • same-origin: 表示cookie只能同域傳送,不能跨域傳送

  • include: cookie既可以同域傳送,也可以跨域傳送

設定include後, 服務端 response header 中 Access-Control-Allow-Origin 必須設定為request的Origin。否則報錯:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access.
springMVC
V.4.3+ 直接使用註解 @CrossOrigin
參考: http://www.cnblogs.com/cielosun/p/6741307.html
V.4.3- 設定response的header
     response.addHeader("Access-Control-Allow-Origin","*");
     response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
     response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");//30 min