How do I do a CORS on my api?


I noticed that my api is not recieving clientside request and it from something called the Same Origin Policy. I need to implement somthing called a cors. I don’t know how to do this. My api is on a glitch site called message-api


I see you’re using Express. I googled it, and you could try adding something like this in your setup region of server.js:

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");

Here’s my source:

Here’s what I searched online:

Looking at your code, I think you could insert the code above at line 18 of server.js before your server.listen

Hope it helps - let us know!


Um. I still have errors.
Failed to load Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access. The response had HTTP status code 404.

script.js:10 Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type application/json. See for more details.


I think the problem is in the order you’re adding your Express middleware. If the route that’s requiring CORS is defined along with your other routes in api/routes/route.js then the app.use call with the CORS definitions needs to come before where the routes are defined (so right after!/message-api?path=server.js:12:0).


script.js:10 OPTIONS 404 (Not Found) (anonymous) @ script.js:10 Failed to load Response for preflight has invalid HTTP status code 404.
Now the cors error gone. What this mean? It’s on a thing called spark-flow that im testing


Ok. I’m getting an options error… . . .


That url ( as well as the root url ( are both returning 404 status codes, which is why the OPTIONS call is also doing the same. That’s probably because you’re only accepting POSTs to that path in api/routes/route.js (on line 47).


I’m sending a POST in spark-roof:

let xhr = new XMLHttpRequest()"POST", '')
xhr.setRequestHeader('Content-Type', "application/json");
xhr.onreadystatechange = () => {
    if (xhr.status == 200) {
        alert('Reqest succeeded');
    usrnm:'Example Username', 
    psw:'Example Password'


The pre-flight request for CORS sends an OPTIONS request, so when CORS executes it’s getting a 404 from the pre-flight because you’re not handling the OPTIONS method.

My suspicion is that you’ll want to respond to the OPTIONS request appropriately. might be useful for understanding what’s going on between the two projects, and gives some pointers to handling OPTIONS (and specifically CORS) with Express.


Using the magic of your help, I got it working. Thanks, cori! Happy glitching!