1.withCredentials是什么?
credentialwithCredentials是XMLHttpRequest的一个属性,表示跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等)
实际中用途就是跨域请求是要不要携带cookie
2.在需要跨域携带cookie时,要把withCredentials设置为true,比如
var xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.open('GET', 'http://localhost:8888/', true)
xhr.send(null)
3.服务端的设置
只有客户端设置当然不够了,服务端还需要设置两点
1)跨域
既然是跨域请求,服务端要设置Access-Control-Allow-Origin,告诉浏览器允许跨域,而且这个值必须指定域名,不能设置为*
比如你页面所在的域名为http://www.abc.com,服务端的Access-Control-Allow-Origin,必须是http://www.abc.com
2)Access-Control-Allow-Credentials
在响应头中,Access-Control-Allow-Credentials这个值也要设置为true,根据mdn上的说法,只有设置为true的时候,浏览器才会把响应结果暴露给你的js代码
最后看一下服务端的代码,我简单用koa2写了一个
const koa = require('koa2')
const app = new koa()
app.use(async ctx => {
ctx.set('Access-Control-Allow-Origin', 'http://127.0.0.1:5500') // 此处为html页面的地址
ctx.set('Access-Control-Allow-Credentials', true)
const username = ctx.cookies.get('username')
if (username) {
ctx.body = username
} else {
ctx.body = 'no cookie'
}
})
app.listen(8888)
网友评论