axios 请求嵌入请求_如何对每个Axios请求强制使用凭据
axios 请求嵌入请求I was using Axios to interact with an API that set a JWT token.我使用Axios与设置JWT令牌的API进行交互。The API returned the token in a cookie and I quickly figured I needed to set withCredentials: t...
axios 请求嵌入请求
I was using Axios to interact with an API that set a JWT token.
我使用Axios与设置JWT令牌的API进行交互。
The API returned the token in a cookie and I quickly figured I needed to set withCredentials: true
in the Axios options:
该API在cookie中返回了令牌,我很快就想出需要在Axios选项中设置withCredentials: true
:
import axios from 'axios'
axios.post(API_SERVER + '/login', { email, password }, { withCredentials: true })
Otherwise the cookie would not be saved.
否则,cookie将无法保存。
I also needed to set it for every other request I made, to send the JWT token to the server:
我还需要为我提出的所有其他请求设置它,以将JWT令牌发送到服务器:
axios.get(API_SERVER + '/todos', { withCredentials: true })
Now, it’s ok for a few requests, but for many, you’d probably like to use a general configuration.
现在,可以接受一些请求,但是对于许多请求,您可能希望使用常规配置。
You can do it using the create()
method to create a new Axios instance you’ll then use it in your requests:
您可以使用create()
方法创建新的Axios实例,然后在请求中使用它:
import axios from 'axios'
const instance = axios.create({
withCredentials: true
})
instance.get(API_SERVER + '/todos')
It’s also common to add a baseURL
property:
添加baseURL
属性也很常见:
import axios from 'axios'
const instance = axios.create({
withCredentials: true,
baseURL: API_SERVER
})
instance.get('todos')
In React I used axios-hooks
, and to configure withCredentials
I used this code:
在React中,我使用axios-hooks
,并使用以下代码配置withCredentials
:
import axios from 'axios'
import useAxios, { configure } from 'axios-hooks'
const instance = axios.create({
withCredentials: true,
baseURL: API_SERVER,
})
configure({ instance })
const [{ data, loading, error }, refetch] = useAxios('todos')
axios 请求嵌入请求
更多推荐
所有评论(0)