The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

artesian (2) [Avatar] Offline
#1
I have MEAP v6 and I recently cloned the ch04 github repo.

I have the Node/Express simple-server running, thanks largely to other posts on this forum.

It took me awhile to figure out that I could just put localhost:3000 into my browser and up comes the app - the behavior matches the text of chapter 4. For others struggling with this, look at the file simple-server/public/index.html in the githup code. It looks like the MEAP text.

Ok, of course, the html is served up by the server. I was following the approach of chapters 1-3 and working with a file - trying to just run the examples from a file, and hitting the server with $http.get('/login').

That approach doesn't work (at least in Chrome). The error on the console is "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

I did some googling and it seems this error needs to be fixed in the Express config in simple-server. Does anyone know how to do that? There's an article below that is close, but I can't figure out where to put the suggested app.configure() code.

http://stackoverflow.com/questions/11001817/allow-cors-rest-request-to-a-express-node-js-application-on-heroku
artesian (2) [Avatar] Offline
#2
Re: Chapter 4 CORS error when running from a file
For anyone else who might encounter this, adding the following lines to ch04/simple-server/app.js fixed it:

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});

This tells Express to return an Access-Control-Allow-Origin header in the response. Which allows you to run the samples from a file.

You obviously would only do this in development, and I'm sure there is a more elegant way to achieve the same effect. If anyone knows how please chime in.