如何在 nodejs express 重定向上启用 CORS?

Zha*_* Yi 5 amazon-s3 node.js cors express

我在后端使用 nodejs express 作为我的 API。我想知道如何在redirect方法上启用 CORS 。

以下是我的快速重定向代码:

res.redirect(redirectUrl);
Run Code Online (Sandbox Code Playgroud)

当客户端向上述 API 发送请求时,它会将请求重定向到 as3但我收到以下错误:

Access to XMLHttpRequest at 'https://s3-ap-southeast-
2.amazonaws.com/index.html' (redirected from 
'http://localhost:9090/v0/api') from origin 'http://localhost:9090' 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.
Run Code Online (Sandbox Code Playgroud)

前端正在运行,http://localhost:9090并且前端域已添加到 s3 存储桶中的 CORS 上。如果我https://s3-ap-southeast-2.amazonaws.com/index.html直接从浏览器发送请求,它工作正常。所以我认为问题出在nodejs express redirect方法上。如何为重定向启用 CORS?

我知道如何启用,CORS但我的问题与redirect. 我怎样才能使重定向工作?

Sar*_*aaz 4

这与您的后端或前端无关,您必须在 S3 存储桶中添加 CORS 策略

请按照以下步骤在您的 S3 存储桶上启用 CORS

  1. 登录 AWS 管理控制台并通过以下网址打开 Amazon S3 控制台:https://console.aws.amazon.com/s3/

  2. 在存储桶名称列表中,选择要为其创建存储桶策略的存储桶的名称。

  3. 选择权限,然后选择 CORS 配置。

  4. 在 CORS 配置编辑器文本框中,键入或复制并粘贴新的 CORS 配置,或编辑现有配置以使其如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)
  1. 选择保存。

这应该对你有用。

参考:https ://docs.aws.amazon.com/AmazonS3/latest/user-guide/add-cors-configuration.html