首页 > 解决方案 > 如何在 nodejs express 重定向上启用 CORS?

问题描述

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

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

res.redirect(redirectUrl);

当客户端向上述 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.

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

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

标签: node.jsexpressamazon-s3cors

解决方案


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

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

  1. 登录 AWS 管理控制台并在https://console.aws.amazon.com/s3/打开 Amazon S3 控制台。

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

  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>
  1. 选择保存。

这应该适合你。

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


推荐阅读