This is my axios configuration:
import axios from "axios"
const axiosApi = axios.create({
baseURL: import.meta.env.VITE_API_URL
})
const requestInterceptor = config => {
config.headers['Content-Type'] = 'application/json';
config.headers['Accept'] = 'application/json';
config.headers['X-Client'] = 'React';
return config;
}
axiosApi.interceptors.request.use(requestInterceptor);
const get = async (url) => {
return await
axiosApi.get(url, {
crossDomain: true
}).then(response => {
return response?.data;
})
}
const post = async (url, data) => {
return await axiosApi
.post(url, Array.isArray(data) ? [...data] : { ...data })
.then(response => response?.data)
}
const form = async (url, data) => {
return await axiosApi
.post(url, data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response?.data)
}
As you can see, for post
and get
utility methods I use a request interceptor that sets the default values. Thus I use Content-Type: application/json
for them.
However, for form
I overrode the Content-Type
header to be a form.
I read some other questions, including:
Axios not passing Content-Type header
Axios Header's Content-Type not set for safari
But my server allows Content-Type
to be sent in CORS requests:
Access-Control-Allow-Headers: authorization,content-type,x-client
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *
But when I use form
method, I see that the Content-Type
is not set to application/json
, not application/x-www-form-urlencoded
.
What have I done wrong?