AWS S3 API请求上托管的React应用失败 [英] React app hosted on AWS S3 API requests fail

查看:46
本文介绍了AWS S3 API请求上托管的React应用失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 create-react-app 编写一个(单页)react应用程序,它调用了我的API,即AWS api网关和AWS lambda.我正在尝试使用AWS s3静态托管来托管react应用.

I'm writing a (single page) react app with create-react-app and it makes calls to my API which is AWS api gateway and AWS lambda. I'm trying to host the react app with AWS s3 static hosting.

在本地进行开发时,由于缺少CORS标头,对我的API的请求(使用 axios )被阻止了.要解决此问题,我在 package.json 文件中将代理添加到了我的AWS api网关域:

When developing locally, requests (with axios) to my API are blocked because of missing CORS headers. To work around this I added a proxy to my AWS api gateway domain in my package.json file:

"proxy": "https://***.execute-api.us-east-2.amazonaws.com/"

因此,请求在我的本地主机上运行,​​该主机将应用程序托管在节点开发服务器上.但是当应用程序托管在AWS S3上时,我无法使它正常工作.对我的API的 axios 请求始终失败,并出现 403 Access拒绝错误.

So requests work on my localhost where the app is hosted on a node development server. But I can't get this to work when the app is hosted on AWS S3. The axios requests to my API always fail with 403 Access denied errors.

我的问题是,为什么请求失败,该如何解决?

My question is, why are the requests failing, and what can I do to fix this?

我能够通过以下方法使我的一种API方法起作用:1)在API网关中为有问题的方法启用CORS,并使我的API返回标头:

I was able to get one of my API methods working by 1) enabling CORS in API gateway for the method in question and having my API return the headers:

{
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*'
}

带有方法响应.

现在,即使进行了上述更改,我的一种POST方法也无法使用,我得到了405个不允许的方法"响应.我真的不知道我是否走在正确的轨道上.

Now one of my POST methods isn't working at all even with the above changes, I'm getting a 405 "method not allowed" response. I really have no idea if I'm on the right track or not.

推荐答案

由于请求来自S3域,因此您需要在API上启用CORS https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

You need to enable CORS on your API as your request are originating from an S3 domain https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

这篇关于AWS S3 API请求上托管的React应用失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆