Enterprise Integration Zone is brought to you in partnership with:

Diego Fernandez is an interaction designer and UI developer working at Mulesoft. He loves design in its many forms: from object oriented design to graphic design. Before joining Mulesoft, Diego worked on UI design and systems development for different industries like travel and financial. He also loves programming languages and had experience with Java, Smalltalk, Scala, Groovy, and more. Diego is a DZone MVB and is not an employee of DZone and has posted 2 posts at DZone. You can read more from them at their website. View Full User Profile

Cross domain REST calls using CORS

12.11.2012
| 2848 views |
  • submit to reddit
To fight XSS attacks, the web browser imposes the same origin policy for HTTP requests made by JavaScript code:

But there are a lot of use cases where this kind of cross domain HTTP request is desired, so developers came up with some workarounds:

  • Server side proxy: the idea is to avoid cross domain requests in the browser by doing them
    on the server:

    To do that in Mule you can use the HTTP proxy pattern as explained in this post.

  • JSONP: it consists of adding a <SCRIPT> tag dynamically. The src attribute of the script tag can point to another domain, and the browser will load and execute the JavaScript code that comes from it. But here is the twist: since the script can be generated dynamically on the server, you can use it to pass data to the JavaScript program in the browser.
    The suffix means padding, because the server needs to pad the returned JSON with a function call to make it a executable JavaScript code.Then your JavaScript code provides the definition of the function that gets called with the data.
    Clever trick right? But it has some limitations: only GET requests can be done in this way.

Is there another option?

Fortunately, yes. Modern browsers supports a W3C Working Draft  called CORS: Cross-Origin Resource Sharing, and probably the browser that you are using to see this page already supports it.

How CORS works?

The browser sends the request adding the Origin header:

GET /api/list HTTP/1.1
Host: myapp.com
User-Agent: Mozilla/5.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: http://myapp.com

If the origin is accepted by the  HTTP server it adds the Access-Control-Allow-Origin header to the response:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://myapp.com
Content-Type: application/json; charset=utf-8

When the browser receives this header it continues reading the payload of the HTTP response, if not the request is rejected.

How it looks in your JavaScript code? If you use jQuery is business as usual:

$.getJSON('http://myapi.com/api/list',
          function (data) { console.log(data); });

jQuery is smart enough to detect the kind of CORS support that your browser has and uses XMLHttpRequest or XDomainRequest if the page is running in IE8.

“You’re allowed a wand…”

In Harry Potter and the Goblet of Fire movie, there is an scene were Harry is about to fight a dragon, and he best chance to win is to flight with the broom:

Harry: – But I’m not allowed a broom.
Professor Moody: – You’re allowed a wand…

Having access to an external domain in your JavaScript code, is like having a wand. Even if your web server is limited to deliver static HTML content, you can create powerful web applications using JavaScript and APIs located elsewhere.

I’m going to show you that with a simple example. It consist of a HTML file shared on Dropbox, which is not a hosting service but allows you to share static content. And from that file we are going to call a service hosted in .

Create a Cloudhub application using MuleStudio

Create a new project with MuleStudio and add a flow with a HTTP endpoint. To make it work with Cloudhub you have to use ${http.port} as port number for the endpoint:

Expose your REST API

In this example I’m going to use a JAX-RS, just because I’ve a background on Java programming and I’ve used JAX-RS services before. But, a good alternative to try is the REST module from MuleForge.

Following the JAX-RS way of things, we need a Java class to define the resources:

package com.mulesoft.blog.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/example")
public class ExampleResource {
  @GET
  @Path("/values")
  @Produces(MediaType.APPLICATION_JSON)
  public String values() {
    return "["Hello", "from other domain"]";
  }
}

Then we need to wire it into the flow using a REST component:

Add Access-Control-Allow-Origin header to the response

An here comes the most important part, we need to add the Access-Control-Allow-Origin header to the response. To do that we are going to use a HTTP Response Builder:

In this case we are using https://dl.dropbox.com. Take account that: you can put multiple origins separated by space, and that http is a different origin than https.

Deploy to Cloudhub

On MuleStudio, right click into the project and choose “Deploy to Cloudhub…”

Fill up the credentials, and we are done with the service. Next step the client code.

Client code

The client code is straight forward:

$(function () {
     var ul = $('<ul></ul>');
     $.getJSON('http://corsexample.cloudhub.io/example/values')
        .then(function (data) {
            data.forEach(function (item) {
                 ul.append('<li>'+item+'</li>'); }) });
     $('body').append(ul);
});

This example takes the list returned by the server and shows a list from it.

You can see the running example here. That’s all folks!



Published at DZone with permission of Diego Fernandez, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)