I keep trying to set up REST APIs to add functionality to static web pages, and each time I do, I inevitably run into the dreaded “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://someaddress/api. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).” error. It seems like no matter how I try to set things up, I can’t wrap my head around exactly why this is happening or how to get around it. I know the API server has to send the aformentioned header, but I get the error even when I have it.
Here’s a recent example. I’m trying to add a simple hit tracker to my personal portfolio website so I can see how often it’s viewed. It’s a static website, so I set up an Express server to handle this job. I send a post request, it updates the hit count. Easy. Or so I naively think.
function addHit() {
let options = {
method: "POST",
body: JSON.stringify({}),
};
fetch("https://myapi.com/hit", options);
}
This gets called on page load. The request is sent here:
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const corsOptions = {
origin: "https://www.mywebsite.com",
};
app.post("/hit", cors(corsOptions), (req, res) => {
//etc...
This actually seems to work… Hits increment, etc. But about 30 seconds after success, the aforementioned CORS error shows up in the console. Manually adding the Access-Control-Allow-Origin header makes no difference.
I really don’t get what’s going on with CORS. I get errors WAY more often than not. Any explanation on how to fix the above error and actually set this up properly every time would be very much appreciated.
Edit: Just tried the below as well, with the same result.
const express = require("express");
const app = express();
const mongoose = require("mongoose");
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "https://www.mywebsite.com");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.post("/hit", (req, res) => {
// etc...
Edit 2: Same result with this
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
app.use(cors());
app.post("/hit", (req, res) => {
// etc...