6

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.

Bishonen_PL
  • 1,400
  • 4
  • 18
  • 31

4 Answers4

9

@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
        }
    }),
Rogelio Triviño
  • 5,961
  • 3
  • 22
  • 17
8

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
  • 35,762
  • 5
  • 67
  • 81
1

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"],
}),
0

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;
  },
});


 `
Aman Jha
  • 308
  • 4
  • 4