Trying to follow the rather sparse tutorial on the official page doesn't get me far.
I'm essentially trying to add a certain header based on the params of an api call, but am clueless how to configure the endpoints to do so.
Trying to follow the rather sparse tutorial on the official page doesn't get me far.
I'm essentially trying to add a certain header based on the params of an api call, but am clueless how to configure the endpoints to do so.
Everything you return
from you endpoint's query
function will be passed as the first argument to your baseQuery
. So if you are using fetchBaseQuery
, you need to take a look at that.
Generally, a baseQuery created by fetchBaseQuery
takes all the options that a normal fetch
call would take - including a headers
field.
So you would have something like
myEndpoint: build.query({
query(args) {
return {
url: "foo",
headers: { myHeader: args.blup }
}
}
})
should do the trick.
Generally, besides the "sparse tutorial", there are about 25 more documentation pages when you scroll down - but even then it's difficult to cover everythin, as RTK-Query is rather flexible.
You can read more on fetchBaseQuery in the docs here: https://redux-toolkit.js.org/rtk-query/api/fetchBaseQuery#using-fetchbasequery
@phry response not working on my case. Checking docs, this make the trick, in my case to resolve a CORS problem:
baseQuery: fetchBaseQuery({
baseUrl: '.....',
prepareHeaders: (headers, { getState }) => {
headers.set('Access-Control-Allow-Origin', '*')
return headers
}
}),
You can use prepareHeaders. This worked for me.
createYourEndPoint: builder.mutation({
query: (body) => ({
url: `youEndPoint`,
method: "POST",
body,
prepareHeaders: (headers) => {
headers.set("Content-Type", "multipart/form-data")
return headers
},
}),
invalidatesTags: ["YourEndPointTag"],
}),
You can use prepareHeaders which is the second arg of fetchBaseQuery
to customize the header as you need:
`
const baseQuery = fetchBaseQuery({
baseUrl: "",
prepareHeaders: (headers) => {
headers.set("Content-type", "appliation/json"),
headers.set("businessUnit", "EUS,MPS"),
headers.set("auth-token", tokenService.getLocalAccessToken());
return headers;
},
});
`
Here is my own example assuming your query is getUserProfile and you are pulling the values for token, userId and your custom header keys from the query params.
getUserProfile: builder.query({
query: (params) => ({
url: `user/${params.userId}`,
method: "GET",
headers: {
Authorization: `Bearer ${params.token}`,
"your-custom-header": params.customKey
},
}),
}),
© 2022 - 2024 — McMap. All rights reserved.