login({ commit }, userInfo) { const { username, password } = userInfo return new Promise((resolve, reject) => { login({ username: username.trim(), password: password }).then(response => { const { data } = response commit('SET_TOKEN', data.token) setToken(data.token) resolve() }).catch(error => { reject(error) }) }) }, 让该请求携带cookie 如何处理
时间: 2024-03-09 22:47:21 浏览: 292
如果要让该请求携带 cookie,我们可以使用 axios 来发送请求,并在请求头中带上 cookie。具体做法如下:
1. 在发送请求前,先从 cookie 中获取 token,并设置到请求头中:
```javascript
import { getCookie } from '@/utils/cookie'
const token = getCookie('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
```
2. 在登录成功后,将服务器返回的 token 存储到 cookie 中:
```javascript
import { setCookie } from '@/utils/cookie'
const { data } = response
setCookie('token', data.token, 7)
```
下面是整个函数的代码示例:
```javascript
import axios from 'axios'
import { setCookie, getCookie } from '@/utils/cookie'
export function login({ commit }, userInfo) {
const { username, password } = userInfo
const config = {
headers: {
'Content-Type': 'application/json'
}
}
// 从 cookie 中获取 token,设置到请求头中
const token = getCookie('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return new Promise((resolve, reject) => {
axios.post('/api/login', {
username: username.trim(),
password: password
}, config).then(response => {
const { data } = response
commit('SET_TOKEN', data.token)
setCookie('token', data.token, 7) // 将 token 存储到 cookie 中
resolve()
}).catch(error => {
reject(error)
})
})
}
```
这样,我们就可以让该请求携带 cookie 了。
阅读全文