Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

跨越请求中的cookie #15

Open
Yang03 opened this issue Mar 29, 2017 · 0 comments
Open

跨越请求中的cookie #15

Yang03 opened this issue Mar 29, 2017 · 0 comments

Comments

@Yang03
Copy link
Owner

Yang03 commented Mar 29, 2017

跨域请求浏览器默认是不发送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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant