In the last post I showed you how to start a new REST project with a Node.js server and Express framework. Doing just this will not do all the work needed if you plan to expose the service to other origins or let external users use it. You need to allow CORS just like I did in this post on a .Net REST service.
The Express framework gives you a way to allow CORS very easily to your REST service using its middleware abilities. A middleware is just a function (or a set of functions which run one after the other) and do some action. This action can depend on some data or state coming from the request or the response, it can be just logging, or it can be error handling.
In order to allow CORS, let us add a middleware function just above our method request routing functions like this:
This function will be called just before we enter the routing functions. We get three parameters:
- req – the request as received from the client (where ever the client sits)
- res – the response that should be returned to the client
- next – a delegate function to be executed. This is the routing function that should be executed.
Inside this middleware we can even control whether we want to execute it if some conditions are not ready.
Inside the middleware function I call the setHeader function on the response and set the ‘Access-Control-Allow-Origin’ header to be ‘*’ which means any. Any client will be able to use this REST service.
Last I call the routing function using the next function delegate.
Now the REST service is open for public.