reactjs - AWS Lambda 和 .Net Core WebAPI 出现 Cors 错误
问题描述
我创建了一个 .Net Core、AWS Lambda WebAPI。在本地测试时,我遇到了一个 CORS 问题并添加了一个 CORS 策略以允许来自我的域的来源。这行得通。该应用程序运行正常。
我需要帮助解决部署后出现的 cors 问题。部署到 AWS 后,我收到了众所周知的错误:
> Access to XMLHttpRequest at 'https://myLambdaEndpoint' from origin
> 'http://myWebsite' 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.
这是我所做的:
我在 React 中使用 Axios 的请求:
axios.post(`myEndpoint`, { FirstName, LastName, Email })
.then(res => {
if(res.errors && res.errors.length > 0) console.log(res.errors);
else
{
this.setState({loading: false, registered: true});
}
})
.catch(err => {alert(err); console.log(err)});
}
//Also tried
axios.post(`myEndpoint`, {headers: {'Access-Control-Allow-Origin': '*'}, FirstName, LastName, Email })
.then(res => {
if(res.errors && res.errors.length > 0) console.log(res.errors);
else
{
this.setState({loading: false, registered: true});
}
})
.catch(err => {alert(err); console.log(err)});
}
在 Startup.cs --> 配置服务
services.addCors()
// Also tried
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder =>
{
builder.WithOrigins("http://myWebsite")
.AllowAnyHeader()
.WithMethods("POST");
});
});
在控制器.cs
[EnableCors(origins: "http://myWebsite", headers: "*", methods: "post")]
我的 API 和网站的 s3 存储桶 cors 政策
<CORSRule>
<AllowedOrigin>myWebsite</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
//Also tried
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
我也尝试在 aws 中向 lambda 函数添加触发器。
预检的状态码是 500。还说“Referer Policy: no-referer-when-downgrade” 我想知道这是否是问题所在?
响应头是:
> Access-Control-Request-Headers: content-type
> Access-Control-Request-Method: POST
> Origin: http://myWebsite.com
> Referer: http://myWebsite.com/
有人知道怎么修这个东西吗?我花了几个小时尝试和完成搜索。
解决方案
只是想在一整天后添加这个问题(.NET Core 5 lambda 函数)。不要在源域末尾添加“/”。即 不要这样做:
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder =>
{
builder.WithOrigins("http://myWebsite/")
.AllowAnyHeader()
.WithMethods("POST");
});
});
应该是这样的:
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder =>
{
builder.WithOrigins("http://myWebsite")
.AllowAnyHeader()
.WithMethods("POST");
});
});
我知道他们在这个问题上没有这样做,但我希望如果他们犯了同样的愚蠢错误,这可能会在未来为其他人节省一些时间。
推荐阅读
- swift - Swift 应用程序调试:在 OSX 10.15 上调用 NSWorkspace.shared.open 被拒绝
- javascript - 单击上一页中的按钮路由到该页面后如何刷新页面
- r - 在 R 中查找 ID 匹配并重塑数据
- php - 需要帮助从 wordpress 中的子文件夹递归渲染图像
- r - 如何从数据中子集列
- sorting - Google Scripts - 排序但不区分大小写
- firefox - Firefox 一直重定向到 https
- python - 无法找到或加载主类 org.apache.nutch.tools.FileDumper
- javascript - 如何使用在别处定义的函数来定义 Javascript 类静态方法?
- shell - 在 Linux Mint 中更改默认 shell