CORS on a Node.js server

18/04/2016

2 תגובות

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.

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

2 תגובות

  1. מנעולן באשדוד18/08/2016 ב 16:26

    פוסט גדול הסברת לי בדיוק מה שהייתי צריך תודה.

    Reply
  2. dor cohen20/08/2016 ב 06:46

    Normally I don’t learn article on blogs, however I wish to say that this write-up very pressured me to check out and do it! Your writing style has been surprised me. Thanks, very great post.

    Reply