Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

CORS node js

Hi, i have built a node JS express API function

it has a post method but when I send the request i get an error 

Referrer Policy:
strict-origin-when-cross-origin
how can I solve this and how cloud functions support Cors module?

thanks

0 2 2,496
2 REPLIES 2

You'll need to handle the CORS request in the function.

Here's an example for gen1:
https://cloud.google.com/functions/docs/samples/functions-http-cors-auth

and another for gen2:
https://cloud.google.com/functions/docs/samples/functions-http-cors#functions_http_cors-nodejs

These samples won't advise as to the specific constraints you'll want (i.e. the Access-Control-Allow-Origin header), but for that you can just refer to general CORS guidance:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Hi @SnowRanger11,

Welcome to Google Cloud Community!

To allow the browser to send a request to your Node.js server from a different origin (domain), you will need to include the appropriate CORS (Cross-Origin Resource Sharing) headers in the server response.
 
You can use the `cors` module to easily enable CORS in your Express.js server.
 
First, install the `cors` module:
npm install cors
 
Then, require the module in your server file and use it as middleware:
const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

// Your routes go here

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
This will allow any origin to send a request to your server. If you want to be more restrictive and only allow certain origins, you can pass an options object to the `cors` function. For example:
app.use(cors({
  origin: 'http://example.com'
}));
This will only allow requests from `http://example.com` to be sent to your server.
 
As for Cloud Functions, they already have CORS enabled by default. You do not need to do anything to enable CORS for your Cloud Functions HTTP triggers. However, if you want to customize the CORS behavior for your function, you can use the `cors` function from the `@google-cloud/functions-framework` package. Here is an example of how you can use it:
const { cors } = require('@google-cloud/functions-framework');

exports.myFunction = cors((req, res) => {
  // Your function logic goes here
});
This will enable CORS for the `myFunction` Cloud Function and allow any origin to send a request to it. You can also pass an options object to the `cors` function to customize the CORS behavior.
 
For example:
const { cors } = require('@google-cloud/functions-framework');

exports.myFunction = cors((req, res) => {
  // Your function logic goes here
}, {
  origin: 'http://example.com'
});
This will only allow requests from `http://example.com` to be sent to the myFunction Cloud Function.
 
Thank you