No 'Access-Control-Allow-Origin' header

For my MERN project, both frontend deploy and backend deploy succeeded, but when I try to fetch backend api by my frontend and Postman, I keep receive the following error :

Access to XMLHttpRequest has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I have confirmed my react path rewrite is corrected in static site and my database is connected.

My original cors config in backend:

const express = require("express");
const app = express();
const cors = require("cors");
app.use(cors());

To fix the above error, I tried to revise it as below:

const express = require("express");
const app = express();
const cors = require("cors");
const corsOptions = {
  origin: /\.onrender\.com$/,
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",};
app.use(cors(corsOptions));

But still

Access to XMLHttpRequest has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.net::ERR_FAILED 503

my service logs:

Jun 15 02:16:56 PM  yarn install v1.22.5
Jun 15 02:16:56 PM  info No lockfile found.
Jun 15 02:16:56 PM  [1/5] Validating package.json...
Jun 15 02:16:56 PM  [2/5] Resolving packages...
Jun 15 02:17:08 PM  [3/5] Fetching packages...
Jun 15 02:17:20 PM  info fsevents@2.3.2: The platform "linux" is incompatible with this module.
Jun 15 02:17:20 PM  info "fsevents@2.3.2" is an optional dependency and failed compatibility check. Excluding it from installation.
Jun 15 02:17:20 PM  [4/5] Linking dependencies...
Jun 15 02:17:20 PM  warning Workspaces can only be enabled in private projects.
Jun 15 02:17:25 PM  [5/5] Building fresh packages...
Jun 15 02:17:26 PM  success Saved lockfile.
Jun 15 02:17:26 PM  Done in 30.05s.
Jun 15 02:17:27 PM  ==> Uploading build...
Jun 15 02:17:36 PM  ==> Build uploaded in 8s
Jun 15 02:17:36 PM  ==> Build successful 🎉
Jun 15 02:17:36 PM  ==> Deploying...
Jun 15 02:18:03 PM  ==> Using Node version 20.3.0 via /opt/render/project/src/package.json
Jun 15 02:18:03 PM  ==> Docs on specifying a Node version: https://render.com/docs/node-version
Jun 15 02:18:03 PM  ==> Starting service with 'npm run server'
Jun 15 02:18:07 PM  
Jun 15 02:18:07 PM  > badmintown@1.0.0 server
Jun 15 02:18:07 PM  > node index.js
Jun 15 02:18:07 PM  
Jun 15 02:18:13 PM  Server runs on port 10000
Jun 15 02:18:14 PM  db is connected

Any suggestions would be highly appreciated. :pray:

1 Like

Hi,

I’ve replied to the ticket you also opened, let’s keep the conversation in one place (on the ticket), then you can update this post with your solution once it’s resolved.

Alan

My deployment works fine now, so I would like to share how I managed to solve these issues.

To be clarified, this is my solutions based on my assumptions that may not works perfectly in other case. If there are some context incorrect, feel free to point out.

Issues that I met:

  1. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
  2. Preflight request warning
  3. Timed out after waiting for internal health check to return a successful response code

My solution for “No ‘Access-Control-Allow-Origin’ header” :

const express = require("express");
const app = express();
// Set middleware of CORS 
app.use((req, res, next) => {
  res.setHeader(
    "Access-Control-Allow-Origin",
    "https://your-frontend.com"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS,CONNECT,TRACE"
  );
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, X-Content-Type-Options, Accept, X-Requested-With, Origin, Access-Control-Request-Method, Access-Control-Request-Headers"
  );
  res.setHeader("Access-Control-Allow-Credentials", true);
  res.setHeader("Access-Control-Allow-Private-Network", true);
  //  Firefox caps this at 24 hours (86400 seconds). Chromium (starting in v76) caps at 2 hours (7200 seconds). The default value is 5 seconds.
  res.setHeader("Access-Control-Max-Age", 7200);

  next();
});
To fix preflight request warning

Introduction about preflight request

I tried to connect my static site on render to my local server for debugging my request on my browser developer tool. The following code works fine on Firefox, but Chrome seems to send preflight request twice with one fail and one succeed which turns out to be a bug on chrome itself.

// Set preflight
app.options("*", (req, res) => {
  console.log("preflight");
  if (
    req.headers.origin === "https://badmintown.onrender.com" &&
    allowMethods.includes(req.headers["access-control-request-method"]) &&
    allowHeaders.includes(req.headers["access-control-request-headers"])
  ) {
    console.log("pass");
    return res.status(204).send();
  } else {
    console.log("fail");
 
To solve health check timeout

According to health check:

What you return on your health check path is up to you, but we recommend running quick sanity checks (like a simple database query) and returning an “OK” 200 response or an empty 204 response if the app is healthy.

To make the health check process faster, I wrote path for it:

app.get("/healthz", (req, res) => {
  console.log("health check is processed");
  return res.status(204).send();
});
Why I set CORS manually

At the beginning, I used node.js package CORS to configure CORS as below:

const express = require("express");
const app = express();
const cors = require("cors");
const corsOptions = {
  origin:"https://your-frontend.com",
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",};
app.use(cors(corsOptions));

However, this did not work and the error kept showing as:

Access to XMLHttpRequest has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Therefore, I assumed that this package may not work successfully during deployment, so I tried to code my CORS configuration manually.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.