Let's say something like this is being returned when a web app is submitting a request to your NodeJS app.In this example:
- http://app.example.com/my/endpoint is the URL of the web app submitting the request to your NodeJS app
- http://node.example.com/my/endpoint is the URL of your NodeJS app that processes the request
Access to fetch at 'http://node.example.com/my/endpoint' from origin 'http://app.example.com/my/endpoint' 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 occurs when the client URL and server URL don't match, including the port number. In this case you need to enable your service for CORS (Cross Origin Resource Sharing).
"preflight" means that before the browser attempt the POST request, 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 Autorization 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
First I added cors to 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 got installed.
npm install
And then I updated the NodeJS 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