Allowing CORS requests for my Express/Node app

I’ve been unsuccessfully trying to allow my back-end app which returns a JSONP as a response to the ‘./poem’ path for a while. I tried using setHeader() s mentioned on stackoverflow in a middleware function but to no avail. Every attempt has failed and I always get a message like this on the console:

Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.

While I can certainly render my app on the server or use a same origin request (which I’m doing right now), I’d like the API to be used on other websites too, like CodePen.

Could someone with experience with Express and node please point me in the right direction?

Here’s the code on Github: GitHub - imtoobose/terriblepoems: Generates a poem based on markov chains formed by poems from Shakespeare or a random poet
Here’s the live app on Heroku: https://really-awful-poems.herokuapp.com/
Route for JSONP: https://really-awful-poems.herokuapp.com/poem

It’s a bit buggy, but I would like to solve this issue asap. I’ve just started with the back end, so I apologize if this is a really obvious mistake. Also I am aware the source code doesn’t contain the setHeader functions for CORS anymore. Removing or adding them didn’t affect the outcome.

Thanks to anyone who looks at it. :slight_smile:

EDIT: I’m using Mashape to overcome this problem, but I still have no idea how I would do this without it.

@mikethecodegeek made a good random quote api that successfully set the headers you are trying to set.

Here’s the repo for it: https://github.com/mikethecodegeek/random-quote-generator

Check the app.js file to see how he handled it. :slight_smile:

2 Likes

Thanks for the reply and the link! However I’ve tried the same headers (and a few more) and they don’t seem to work. I even put them at the very beginning of my middleware stack.

You don’t currently pass any headers from what I can see on GitHub.

Did you have this before your get requests?

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();
});

I had the headers in an earlier version, which included these ones and a few others I got from stack overflow. They were in a middleware function that i tried calling before the get methods but it didn’t work, so I’ve removed them. This drove me mad for a good amount of time before I just gave up.