How to force the use of credentials for every Axios request

I am using Axios to interact with an API that sets up a JWT token.

The API returned the token in the cookie, and I quickly figured out that it needs to be setwithCredentials: trueIn the Axios options:

import axios from 'axios'

axios.post(API_SERVER + ‘/login’, { email, password }, { withCredentials: true })

Otherwise, the cookie will not be saved.

I also need to set it up for all other requests I make to send the JWT token to the server:

axios.get(API_SERVER + '/todos', { withCredentials: true })

Now, some requests can be accepted, but for many requests, you may want to use the regular configuration.

you can use itcreate()Method to create a new Axios instance, and then use it in the request:

import axios from 'axios'

const instance = axios.create({ withCredentials: true })

instance.get(API_SERVER + ‘/todos’)

add onebaseURLproperty:

import axios from 'axios'

const instance = axios.create({ withCredentials: true, baseURL: API_SERVER })

instance.get(‘todos’)

In React I usedaxios-hooksAnd configurewithCredentialsI used the following code:

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’)

Download mine for freeJavaScript beginner's manual


More js tutorials: