I am building a Next.js 14 app and I got this error with RTK Queries:
login:1 Access to fetch at 'https://XXXXXXXXX.amazonaws.com/dev/login/admin/auth' from origin 'http://localhost:3001' 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.And this is my code :
import { BaseQueryApi, FetchArgs, RootState, createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'import { setCredentials, logOut } from '@/store/slices/auth/authSlice'const baseQuery = fetchBaseQuery({ baseUrl: 'https://xxxxxxxx.amazonaws.com/dev/login/admin', method: 'POST', body: {"emailAddress": "t.m.parakrama+101@gmail.com","password": "Visio@1234" }, credentials: 'include', prepareHeaders: (headers, { getState }) => { const token = getState().auth.token if (token) { //headers.set("authorization", `Bearer ${token}`) headers.set("x-api-key", `XXXXXXXXXX`) } return headers }})const baseQueryWithReauth = async (args, api, extraOptions) => { let result = await baseQuery(args, api, extraOptions) if (result?.error?.originalStatus === 403) { console.log('sending refresh token') const refreshResult = await baseQuery('/refresh', api, extraOptions) console.log(refreshResult) if (refreshResult?.data) { const user = api.getState().auth.user api.dispatch(setCredentials({ ...refreshResult.data, user })) result = await baseQuery(args, api, extraOptions) } else { api.dispatch(logOut()) } } return result}export const apiSlice = createApi({ baseQuery: baseQueryWithReauth, endpoints: builder => ({})})I think there is an error with my code, here I am using RTK Query but if I Use axios this error won't happen. Can you help me to fix this issue ?
This is the code with axios :
const axios = require('axios');const baseQuery = async (getState) => { // Extract the token from the state const token = getState().auth.token; // Prepare the headers const headers = {'Content-Type': 'application/json', }; if (token) { // headers['Authorization'] = `Bearer ${token}`; headers['x-api-key'] = 'WhKzV4ZUxo8w7ytO5kQt169pQhDHQlBf4TiDrFIF'; } // Make the POST request using Axios try { const response = await axios.post('https://8o269xr9e2.execute-api.ap-southeast-1.amazonaws.com/dev/login/admin', { emailAddress: 't.m.parakrama+101@gmail.com', password: 'Visio@1234', }, { headers: headers, withCredentials: true, } ); return response.data; } catch (error) { console.error('Error making request:', error); throw error; }};(when I use axios cors error wont happen)