0

I want to enable cors for a google cloud function. My index.js is:

const cors = require('cors');

exports.helloWorld = function helloWorld(req, res) {
  if (req.body.message === undefined) {
    console.log('No message defined!');
  } else {
    console.log(req.body.message);    
  }

//res.set('Access-Control-Allow-Origin', "*");
//res.set('Access-Control-Allow-Methods', 'GET, POST');

  cors(req, res, () => {
        console.log('inside cors');
        res.status(200).send(users);
    });
  //cors(res.status(200).send(users));

//res.status(200).send(users);
  //res.end();
};

and my package.json:

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "cors": "2.8.4"
    }
}

Based on this link I tried to add the headers manually but with no success. I've also tried this solution but with no prevail.

What am I doing wrong?

florin
  • 469
  • 6
  • 25

1 Answers1

1

The solution was to add the following headers:

res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.set('Access-Control-Allow-Headers', '*');

The solution form this thread was not enough for me. I still received errors: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response

By adding the line res.set('Access-Control-Allow-Headers', '*'); it worked.

florin
  • 469
  • 6
  • 25