Bootstrap FreeKB - Node.js - Resolve "Access to fetch has been blocked by CORS policy"
Node.js - Resolve "Access to fetch has been blocked by CORS policy"

Updated:   |  Node.js articles

Let's say something like this is being returned when a web app is submitting a request to your Node.js app. In this example:

  • http://app.example.com/foo is the URL of the web app submitting the request to your Node.js app
  • http://node.example.com/bar is the URL of your Node.js app that processes the request
Access to fetch at 'http://node.example.com/bar' from origin 'http://app.example.com/foo' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
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.

 

This error often occurs when the client URL and server URL don't match. Often, this can be resolved by allowing CORS (Cross Origin Resource Sharing).

"preflight" means that before the browser attempt the request (GET / POST / PUT / et cetera), it first sends an OPTIONS request to the server to determine if the server is opting-in to receiving a cross-origin POST that has Authorization and Content-Type: application/json headers. You should be able to replicate this with curl.

curl \
--include \ 
--request OPTIONS \
--header "Origin: http://127.0.0.1:3000" \
--header 'Access-Control-Request-Method: POST' \
--header 'Access-Control-Request-Headers: Content-Type, Authorization' \
--url https://www.example.com

 

Sometimes this can be resolved by adding cors as a dependencies in your Node.js apps package.json.

{
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.0",
    "express": "^4.17.3",
    "node-fetch": "^3.2.1"
  },
  "type": "module"
}

 

And then used the npm install command to install/update the packages in package.json so that CORS gets installed.

npm install

 

And then I updated the Node.js app to import and use CORS. Notice in this example that package.json has "type": "commonjs". WIth CommonJS, you will use require​.

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

 

If package.json had "type": "module" then use import (not require).

import cors from 'cors';
app.use(cors());

 

Additionally, I also updated both web app "a" and web service "b" with header "Access-Control-Allow-Origin": "*".

headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    }

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 45447a in the box below so that we can be sure you are a human.