Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS

I'm am trying to fetch a serverless function from a react app in development mode with the following code.

let response = await fetch(url,
       {
           method: 'POST',
           mode: 'cors',
           body: "param=" + paramVar,
        })
        .then(response => response.json());

The backend function is a Python Cloud function with the following code:

def main(request):
    # CORS handling
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)
    
    # Set CORS headers for the main request
    headers = {
        'Content-Type':'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
    }

    # Process request
    return (json.dumps(response), 200, headers)

But I keep getting the following error:

Access to fetch at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

When I try to perform the same request using curl I get a proper response. Using curl to get the options gives me the following:

HTTP/2 204
access-control-allow-headers: Content-Type
access-control-allow-methods: GET, POST
access-control-allow-origin: *
access-control-max-age: 3600
content-type: text/html; charset=utf-8
date: Sun, 16 Aug 2020 01:29:41 GMT

Anyone can help me understand why I'm not able to get a response at my front-end? The 'Access-Control-Allow-Origin' is present in the headers so I really don't understand what is the cause of this error.

like image 973
lspinheiro Avatar asked Aug 16 '20 02:08

lspinheiro


1 Answers

Install the CORS package in the backend. Then open your server.js file or whatever is yours. Then import it to the file

const cors = require('cors');

And then use it

app.use(cors());

reload the browser and should be done!

like image 99
Atanas Vihrogonov Avatar answered Nov 11 '22 10:11

Atanas Vihrogonov