Redux Toolkit RTK-Query Cors issue
Asked Answered
R

3

7

I'm trying to get data from the public Deezer Api located here : https://api.deezer.com/.

To fetch that data i'm using RTK-Query from reduxtoolkit like so (to then use it in my components using hooks i get from each endpoints) :

export const deezerApi = createApi({
    reducerPath: 'deezerApi',
    baseQuery: fetchBaseQuery({ baseUrl: 'https://api.deezer.com/', 
    mode: "cors", ==> enable cors here
    prepareHeaders: (headers) => {
      headers.set('Access-Control-Allow-Origin', '*') ==> what i tried but still not working
      // headers.set('Access-Control-Allow-Methods', 'GET') //
      // headers.set('Access-Control-Allow-Headers', '*') //
      return headers
    },
  }),
    
    endpoints: (builder) => ({

      
      getChartArtists: builder.query({
        query: () => `chart/artists`,
      }),

// More endpoints 

    }),
    
  })

Here is the error i get :

Access to fetch at 'https://api.deezer.com/chart/albums' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

I get this error whether or not i add this line of code :

headers.set('Access-Control-Allow-Origin', '*')

When i look at the network console, it seems to be added to the header of my request...

enter image description here

Does anyone what's happening or have a solution ?

Thanks for your help !

Richela answered 28/5, 2022 at 6:16 Comment(0)
F
6

If you are certain that your backend has enabled CORS to all domains in dev mode, you might need to adjust your fetchBaseQuery credential like this:

import { fetchBaseQuery } from "@reduxjs/toolkit/query";
import type { BaseQueryFn, FetchArgs, FetchBaseQueryError } from "@reduxjs/toolkit/query";
import { API } from "../common/const";

const baseQuery = fetchBaseQuery({
    baseUrl: API.BASE_URL,
    // crendentials: "include" will face CORS if credential is not provided
    credentials: "same-origin", 
    prepareHeaders: (headers) => {
        const accessToken = localStorage.getItem("token");
        if (accessToken) {
            headers.set("authorization", `Bearer ${accessToken}`);
            headers.set("Content-Type", "application/json");
        }

        return headers;
    },
});

export const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
    args,
    api,
    extraOptions
) => {
    return await baseQuery(args, api, extraOptions);
};
Friede answered 15/1, 2023 at 7:13 Comment(2)
This solved the error, wow you saved me, been stuck for 2 days on this. cheersGarv
it worked for me; in case the cookie or local storage is empty, this key can help.Yasukoyataghan
A
4

After losing a whole day on this I was able to get it to work by changing method: 'patch' to method: 'PATCH'.

I hope this helps somebody.

Aran answered 19/6, 2023 at 7:42 Comment(2)
I can't believe this was the problem, ThanksCoheir
I tried all the other things in this thread, didn't work, until I tried this simple fix and it worked! Thank youFitzger
L
3

CORS headers are response headers, not request header. That means the server has to set them when responding, not the client when asking for a resource. Or: you cannot set them. CORS is a method where the server controls who is allowed to talk to it.

What you can do is enable CORS in the first place. Add mode: "cors" to your fetchBaseQuery arguments.

Loopy answered 28/5, 2022 at 7:17 Comment(3)
Thanks for your answer ! I tried to enable cors like edited in my question but it doesn't seems to work, i still get the same errorRichela
It's very possible that deezer is just not allowing other webpages to access their api. In that case you can't directly access their api and there is no way around that without a third party playing proxy server-side. This answer seems to suggest something like that: https://mcmap.net/q/1137130/-cannot-load-deezer-api-resources-from-localhost-with-the-fetch-apiLoopy
Deezer themselves kinda imply this: support.deezer.com/hc/en-gb/articles/… "My authentication token request is blocked because of CORS. Why?" "It appears you are trying to make a call via Javascript on another domain. If you’d like our API in a JavaScript implementation, please use our Javascript SDK."Loopy

© 2022 - 2024 — McMap. All rights reserved.