Cookie的设置、读取以及是否自动携带问题

栏目: jQuery · 发布时间: 5年前

内容简介:不行! 只能向当前域或者更高级域设置cookie例如读取cookie情况同上

不行! 只能向当前域或者更高级域设置cookie

例如 client.com 不能向 a.client.com 设置cookie, 而 a.client.com 可以向 client.com 设置cookie

读取cookie情况同上

客户端设置cookie与服务端设置cookie有什么区别?

无论是客户端还是服务端, 都只能向自己的域或者更高级域设置cookie 例如 client.com 不能向 server.com 设置cookie, 同样 server.com 也不能向 client.com 设置cookie

服务端可以设置 httpOnly: true , 带有该属性的cookie客户端无法读取

客户端只会带上与请求同域的cookie, 例如 client.com/index.html 会带上 client.com 的cookie, server.com/app.js 会带上 server.com 的cookie, 并且也会带上httpOnly的cookie

但是, 如果是向服务端的ajax请求, 则不会带上cookie, 详情见第三个问题

ajax请求到底会不会带上cookie?

默认情况下不会, 只有当设置了 credentials 时才会带上与请求同域的cookie, 并且服务端需要设置响应头 Access-Control-Allow-Credentials: true , 否则浏览器会报错, 拿不到响应

fetch 设置 credentials

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set). Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.

使fetch带上cookie

fetch(url, {
    credentials: "include", // include, same-origin, omit
})
复制代码
  • include: 跨域ajax带上cookie
  • same-origin: 仅同域ajax带上cookie
  • omit: 任何情况都不带cookie

developer.mozilla.org/en-US/docs/…

axios 设置 credentials

// withCredentials indicates whether or not cross-site Access-Control requests, should be made using credentials // default: withCredentials: false

axios 默认情况下, 请求同域ajax会带上cookie, 跨域ajax不带cookie

使axios带上cookie

axios.get('http://server.com', {withCredentials: true})
复制代码

github.com/axios/axios…


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Machine Learning in Action

Machine Learning in Action

Peter Harrington / Manning Publications / 2012-4-19 / GBP 29.99

It's been said that data is the new "dirt"—the raw material from which and on which you build the structures of the modern world. And like dirt, data can seem like a limitless, undifferentiated mass. ......一起来看看 《Machine Learning in Action》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具