node.jsreactjsfirebase

Firebase error with CORS when running on localhost


I am getting the following error when running my project.

Failed to load https://us-centralx-xxx.cloudfunctions.net/xxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.

After reading many SO post, I found the following solution, where I need to add the Access-Control-Allow-Origin , Access-Control-Allow-Methods , and Access-Control-Allow-Headers

const HEADERS = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':  'http://localhost:3000/',
    'Access-Control-Allow-Methods': 'POST',
    'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
};

However, the error still persist. How can i solve this ?

UPDATE

exports.uploadFile = functions.https.onRequest((req, res) => {
        res.setHeader("Access-Control-Allow-Origin", "*");

        res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');


    res.status(200).json({
        message: req.body
    });
});

Solution

  • In your Node.js server set the appropiate headers to allow controlled CORS requests:

    app.use((req, res, next) => {
      const origin = req.headers.origin;
      // arrayOfValidOrigins is an array of all the URL from where you want to allow 
      // to accept requests. In your case: ['http://localhost:3000'].
      // In case you want to accept requests from everywhere, set:
      // res.setHeader('Access-Control-Allow-Origin', '*');
      if (arrayOfValidOrigins.includes(origin)) {
        res.setHeader('Access-Control-Allow-Origin', origin);
      }
    
      // Here allow all the HTTP methods you want
      res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
      // Here you allow the headers for the HTTP requests to your server
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      // Method to reference to the next Node.js function in your flow
      next();
    });
    

    Another option you have is to use the Express.js CORS package and configure it suitable to your needs.