【发布时间】:2022-01-06 18:55:50
【问题描述】:
我对 React 中的 Redux Tool Kit (RTK) 有疑问。我正在尝试使用 API 密钥向 API Gateway (REST API) 发送请求。 API Gateway 中的 CORS 如下所示:
'Access-Control-Allow-Headers': 'Content-Type,X-Api-Key',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'OPTIONS,POST'
这就是 RTK api 的样子
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
}
}
}),
}),
})
当我尝试在 React 组件中使用 usePostRequestsMutation 挂钩时,我遇到了 403 的 CORS 错误。我在浏览器中进行了检查,并且预检检查查询不包含我在 createApi 块中指定的标题。是否有可能为预检检查查询添加标题?
通过执行以下操作可以重现 403 错误:
curl -v -X OPTIONS https://my-api.execute-api.eu-west-1.amazonaws.com/api/helloworld
上面提到的 curl 将返回403 {"message":"Forbidden"}。当我将带有X-Api-Key 的所需标头添加到OPTIONS 请求时,我得到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
总结一下 - 有没有办法在 RTK 的预检请求中添加 x-api-key 标头?
【问题讨论】:
标签: reactjs amazon-web-services react-redux redux-toolkit rtk-query