Yang03 / blog

0 stars 0 forks source link

跨越请求中的cookie #15

Open Yang03 opened 7 years ago

Yang03 commented 7 years ago

跨域请求浏览器默认是不发送token的(包括HTTP Cookies)的,但是XMLHttpRequest 的属性withCredentials为true 的情况下,浏览器就将允许该请求的发送中带有Cookies。

var xhr = new XMLHttpRequest()
xhr.withCredentials = true
// 或者 jquery
$.ajax({
    xhrFields: {
        withCredentials: true
    }
})

仅仅这样还是不够的, 因为浏览器会发起一个预请求,“预请求”要求必须先发送一个 OPTIONS 方法请求给目的站点,来查明这个跨站请求对于目的站点是不是安全的可接受的。所以你要在服务端,告诉浏览器是安全的。注:(跨域并非浏览器限制了发起跨站请求,而是跨站请求可以正常发起,但是返回结果被浏览器拦截了)

下面以node express的代码为例


app.use((req, res, next) => {
  let origin = req.headers.origin
  // 这里允许a.cn, a.com 发起的跨越请求
  if (origin && (origin.indexOf('a.cn') !== -1 || origin.indexOf('a.com') !== -1)) {
     //withCredentials: true ,Access-Control-Allow-Origin:*  是不允许的
     res.setHeader("Access-Control-Allow-Origin", origin)
     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
     res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
     //这段也是必须的
     res.setHeader('Access-Control-Allow-Credentials', true)
  }
  next()
})

参考: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS