sensitive-blue
sensitive-blue5mo ago

header token auth is not sending in request header

I've got this code import React from "react"; import { DataProvider } from "@refinedev/core"; import axios from "axios"; const axiosInstance = axios.create(); // add token to every request axiosInstance.interceptors.request.use( async (config) => { const token = localStorage.getItem("token"); if (token && config?.headers) { config.headers.Authorization = Bearer ${token}; } return config; }, (error) => { return Promise.reject(error); }, ); export const dataProvider = (url: string): DataProvider => ({ getList: async ({ resource }) => { const response = await axiosInstance.get(${url}/${resource}); const data = response.data; return { data, total: data.length, }; }, getOne: async () => { throw new Error("Not implemented"); }, create: async () => { throw new Error("Not implemented"); }, update: async () => { throw new Error("Not implemented"); }, deleteOne: async () => { throw new Error("Not implemented"); }, getApiUrl: () => url, }); but the request header is not including the bearer token
2 Replies
kapa.ai
kapa.ai5mo ago
Hi @celu99. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The code you provided seems correct for setting the Authorization header with a bearer token. However, there could be a few reasons why the token is not being sent in the request header: 1. The token might not be correctly stored in the local storage. Ensure that the token is being stored correctly and that the key you're using to retrieve it matches the key used when storing it. 2. The token might be null or undefined. This would prevent the if (token && config?.headers) condition from passing, meaning the Authorization header wouldn't be set. You can check this by logging the token value. 3. There might be an issue with the axios instance. Ensure that the axios instance you're using in your requests is the same instance where you've defined the interceptor. If you're still having issues, you could try setting the headers directly in the request, like so:
const response = await axiosInstance.get(`${url}/${resource}`, {
headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
});
const response = await axiosInstance.get(`${url}/${resource}`, {
headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
});
This will directly set the Authorization header for this specific request. For more information on how to handle authentication in Refine, you can refer to the official documentation (https://refine.dev/docs/guides-concepts/data-fetching#authentication-). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@655810325777481823> kapa.ai is still learning and improving, please let us know how it did by reacting below