Dans ma vie trépidante d’expérimentateur fou, je me suis pris au jeu d’utiliser VertX comme serveur REST et AngularJS pour le frontal. Mais alors, me direz vous, qu’en est il des CORS?

Côté Angular

var server ="http://localhost:8080";
angular.module('GiwiApp', ['ngRoute', 'ngSanitize', 'httpModule'])

.config([ '$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.interceptors.push('httpInterceptor');
} ])

.factory('httpInterceptor', [ '$q', function($q) {
    return {
    // Everytime a request starts
        request : function(config) {
            if (config.url.startsWith('/rest')) {
                config.headers['Content-Type'] = 'application/json';
            }
            if (!config.url.startsWith('template/')) {
                if (config.url.startsWith('/')) {
                    config.url = server + config.url;
                } else {
                    config.url = server + '/' + config.url;
                }
            }
            return config || $q.when(config);
        },
        // When a request ends
        response : function(response) {
            return response || $q.when(response);
        },
        // When a request fails
        responseError : function(response) {
            console.error(response);
            return $q.reject(response);
        }
    };
}]);

Côté VertX

public class Main extends Verticle {
    /*
     * (non-Javadoc)
     * 
     * @see org.vertx.java.platform.Verticle#start(org.vertx.java.core.Future)
     */
    @Override
    public void start(final Future startedResult) {
        final HttpServer server = vertx.createHttpServer();
	final RouteMatcher rm = new RouteMatcher();
	rm.get("/", new Handler() {
		@Override
		public void handle(final HttpServerRequest req) {
			enableCors(req);
			req.response().sendFile("web/index.html");
		}
	});
	// Cors
	rm.optionsWithRegEx(".*", new Handler() {
		@Override
		public void handle(final HttpServerRequest req) {
			enableCors(req);
			req.response().end();
		}
	});
	rm.allWithRegEx("^/rest/.*", new Handler() {
		@Override
		public void handle(final HttpServerRequest req) {
			req.bodyHandler(new Handler() {
				@Override
				public void handle(final Buffer event) {
					[...]
					enableCors(req);
					req.response().end(response);
				}
			});
		}
	});
	private void enableCors(HttpServerRequest req) {
		req.response().headers().add("Access-Control-Allow-Origin", "*");
		req.response().headers().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		req.response().headers().add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
	}
    }
}

Et voili voilou.

Partager c'est la vie

Leave a Comment