redux-toolkit
redux-toolkit copied to clipboard
RTK Query - Changing the default header from fetchBaseQuery not working
For almost all endopoints I need the headers.set("Content-Type", "application/json")
but there are also some endpoints such as those for uploading files where I need to replace Content-Type", "application/json
with Content-Type': 'multipart/form-data
.
From what I read in other topics, the content-type is set automatically from FormData, but in my case is not working. I also tried to set it manually but still not working
// api.ts
const baseQuery = fetchBaseQuery({
baseUrl: '/',
headers: { 'Content-Type': 'application/json'},
prepareHeaders: (headers, { getState, endpoint }) => {
// i set this as default for all endpoints
headers.set("Content-Type", "application/json");
const token = (getState() as RootState).auth.access;
if (token && endpoint !== 'refresh') {
headers.set('Authorization', `Token ${token}`);
}
return headers;
}
});
const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
args,
api,
extraOptions
) => {
let result = await baseQuery(args, api, extraOptions);
...rest of the code from reauth
return result
}
const api = createApi({
baseQuery: baseQueryWithReauth,
endpoints: () => ({}),
});
// exampleApi.ts
export const pageApi = api.injectEndpoints({
endpoints: (builder) => ({
uploadMediaPage: builder.mutation<
Partial<ExampleProps>,
{ _id?: string; file: File; type: string; }
>({
query: ({ _id, ...formData }) => {
let bodyFormData = new FormData();
bodyFormData.append('file', formData.file);
bodyFormData.append('type', formData.type);
return {
url: `http://localhost:5000/${_id}/upload/`,
method: 'POST',
body: bodyFormData,
// I tried to set manually but is not overwriting the one from api.ts
headers: {
'Content-Type': 'multipart/form-data',
},
};
},
})
})