Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS on nodejs express redirect?

I am using nodejs express as my API in the backend. I wonder how to enable CORS on redirect method.

Below is my express redirect code:

res.redirect(redirectUrl);

when client sends request to above API it will redirect the request to a s3 but I get below error:

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.

the frontend is running under http://localhost:9090 and the frontend domain has been added on CORS in the s3 bucket. It works fine if I send the request to https://s3-ap-southeast-2.amazonaws.com/index.html directly from the browser. So I think the problem is on nodejs express redirect method. How can I enable CORS for the redirect?

I know how to enable CORS but my problem relates to redirect. How can I make the redirect work?

like image 319
Joey Yi Zhao Avatar asked Dec 14 '18 04:12

Joey Yi Zhao


1 Answers

This has nothing to do with your backend or frontend, you'll have to add CORS policy in your S3 bucket

Please follow below steps to enable CORS on your S3 bucket

  1. Sign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/.

  2. In the Bucket name list, choose the name of the bucket that you want to create a bucket policy for.

  3. Choose Permissions, and then choose CORS configuration.

  4. In the CORS configuration editor text box, type or copy and paste a new CORS configuration, or edit an existing configurationto make it look as below.

<?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. Choose Save.

This should work for you.

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

like image 108
Sarfraaz Avatar answered Nov 15 '22 03:11

Sarfraaz