I have problem with the Redux Tool Kit (RTK) in React. I'm trying to send a request to API Gateway (REST API) with API key. The CORS in API Gateway looks like following:
'Access-Control-Allow-Headers': 'Content-Type,X-Api-Key',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'OPTIONS,POST'
This is how the RTK api looks like
const myApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({
baseUrl: 'https://my-api.execute-api.eu-west-1.amazonaws.com/api',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': 'my-api-key-from-api-gateway',
}
}),
endpoints: (builder) => ({
postRequest: builder.mutation<Response, RequestBody>({
query(body) {
return {
url: '/helloworld',
method: 'POST',
body
}
}
}),
}),
})
When I try to use the usePostRequestsMutation hook in React component, I'm getting CORS errors with 403. I checked in the browser and the preflight check query does NOT contain headers I specified in the createApi block. Is there a possibility to add headers for the preflight check query?
It's possible to reproduce the 403 error, by doing:
curl -v -X OPTIONS https://my-api.execute-api.eu-west-1.amazonaws.com/api/helloworld
The curl mentioned above will return 403 {"message":"Forbidden"}. When I add required header with X-Api-Key to the OPTIONS request, then I get HTTP 200
curl -v -X OPTIONS -H "x-api-key: my-api-key-from-api-gateway" https://my-api.execute-api.eu-west-1.amazonaws.com/api/helloworld
To summarize - is there any way to add x-api-key header to the preflight check request in RTK?