alova请求库携带cookie的方式

1.首先写一个request.ts

2.在请求拦截器配置config.credentials = 'include',这样就可以携带cookie了

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { createAlova } from 'alova'
import VueHook from 'alova/vue'
import GlobalFetch from 'alova/GlobalFetch'
import { Message } from '@arco-design/web-vue'

function getToken() {
let tempToken = ''
return {
get() {
if (tempToken) return tempToken
const token = localStorage.getItem('TOKEN')
if (token) {
tempToken = token
}
return tempToken
},
clear() {
tempToken = ''
}
}
}

export const computedToken = getToken()

export const alovaIns = createAlova({
// 假设我们需要与这个域名的服务器交互
baseURL: '',

// 在vue项目下引入VueHook,它可以帮我们用vue的ref函数创建请求相关的,可以被alova管理的状态
statesHook: VueHook,

// 请求适配器,这里我们使用fetch请求适配器
requestAdapter: GlobalFetch(),

// 设置全局的请求拦截器,与axios相似
beforeRequest({ config }) {
// 假设我们需要添加token到请求头
config.headers.Authorization = `Bearer ${computedToken.get()}`

config.headers['Content-Type'] = 'application/json; charset=utf-8'
config.credentials = 'include'
},

// 响应拦截器,也与axios类似
responsed: async response => {
const json = await response.json()
if (response.status !== 200 || json.code != 0) {
Message.error(json.message)
throw new Error(json.message)
}
return json.data
}
})