Express configured to use CORS does not accept CORS

I’ve got some weird stuff going on with Express. I have an endpoint that takes logging data and shoves it into a postgres db, but I’m getting this error on requests:

Access to XMLHttpRequest at 'https://myserver.com/log' from origin 'https://myorigin.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This doesn’t make any sense because I’ve configured the express app to accept CORS and it looks like options requests are accepted? Here’s the relevant server side code

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use(express.json());

and here’s the request

$.ajax({
    type: "POST",
    url: "https://myserver.com/log",
    data: JSON.stringify({ "username": "test", "json": {a: 1}}),
    dataType: 'json',
    contentType: 'application/json'
})

I have tried

app.use(cors())

and

app.use(cors());
app.options("*", cors());

to no avail.

Is there anything glaringly obvious that I’m missing here?

31 thoughts on “Express configured to use CORS does not accept CORS”

  1. 529009 585980Thanks for some other wonderful post. Where else may just anyone get that type of info in such an ideal means of writing? Ive a presentation next week, and Im at the search for such information. 595252

    Reply

Leave a Comment