vue使用fetch丢失cookies

vue使用fetch 关于cookies丢失的问题

1. 其实这个问题还是个人原因,在官方文档是有解释的,不过自己没有细看英文文档.

The fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.

文档里说道,默认不会发送和接受任何cookies
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. See Sending cookies for how to opt into cookie handling.

2. 查看怎么获取cookies 文档里写到

To automatically send cookies for the current domain, the credentials option must be provided:

fetch('/users', {
  credentials: 'same-origin'
})
The "same-origin" value makes fetch behave similarly to XMLHttpRequest with regards to cookies. Otherwise, cookies won't get sent, resulting in these requests not preserving the authentication session.

For CORS requests, use the "include" value to allow sending credentials to other domains:

fetch('https://example.com:1234/users', {
  credentials: 'include'
})

3. 根据自己的请求类型在请求选项里加如对应的credentials选项就行

XMLHttpRequest
fetch('/users', {
  credentials: 'same-origin'
})
CORS requests
fetch('https://example.com:1234/users', {
  credentials: 'include'
})