How to Bridge Frontend and REST API with Spring Cloud Zuul Proxy

This tutorial demonstrates how to use Spring Cloud Zuul as a proxy to connect a frontend AngularJS application with a separate REST API, addressing CORS and same‑origin restrictions, configuring Maven, routing, custom filters, and testing the integration.

21CTO
21CTO
21CTO
How to Bridge Frontend and REST API with Spring Cloud Zuul Proxy

1. Overview

The article explains how a frontend application can communicate with a separately deployed REST API by using a Zuul proxy to overcome CORS and browser same‑origin policy limitations.

2. Maven Configuration

Add the Spring Cloud Zuul starter dependency to the UI project's pom.xml:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-zuul</artifactId>
  <version>1.0.4.RELEASE</version>
</dependency>

3. Zuul Properties

Configure routing in application.yml:

zuul:
  routes:
    foos:
      path: /foos/**
      url: http://localhost:8081/spring-zuul-foos-resource/foos

4. API Application

A simple Spring Boot API defines a Foo DTO and a controller:

public class Foo {
    private long id;
    private String name;
    // standard getters and setters
}
@Controller
public class FooController {
    @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
    @ResponseBody
    public Foo findById(@PathVariable long id, HttpServletRequest req, HttpServletResponse res) {
        return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4));
    }
}

5. UI Application

The UI is also a Spring Boot app that uses a small AngularJS page to call the API via relative URLs, which only work when routed through Zuul:

<html>
<body ng-app="myApp" ng-controller="mainCtrl">
<script src="angular.min.js"></script>
<script src="angular-resource.min.js"></script>
<script>
var app = angular.module('myApp', ["ngResource"]);
app.controller('mainCtrl', function($scope,$resource,$http) {
    $scope.foo = {id:0 , name:"sample foo"};
    $scope.foos = $resource("/foos/:fooId",{fooId:'@id'});
    $scope.getFoo = function(){
        $scope.foo = $scope.foos.get({fooId:$scope.foo.id});
    }
});
</script>
<div>
<h1>Foo Details</h1>
<span>{{foo.id}}</span>
<span>{{foo.name}}</span>
<a href="#" ng-click="getFoo()">New Foo</a>
</div>
</body>
</html>

The UI runs on port 8080 while the API runs on port 8081; without Zuul the UI cannot reach the API using relative URLs.

6. Enable Zuul Proxy

@EnableZuulProxy
@SpringBootApplication
public class UiApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
    }
}

This annotation cleanly activates Zuul routing.

7. Test Routing

@Test
public void whenSendRequestToFooResource_thenOK() {
    Response response = RestAssured.get("http://localhost:8080/foos/1");
    assertEquals(200, response.getStatusCode());
}

8. Custom Zuul Filter

A simple filter can add custom headers to proxied requests:

@Component
public class CustomZuulFilter extends ZuulFilter {
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.addZuulRequestHeader("Test", "TestSample");
        return null;
    }
    @Override
    public boolean shouldFilter() { return true; }
    // ...
}

9. Test Custom Filter

Modify the API controller to echo the header and verify it:

@Controller
public class FooController {
    @GetMapping("/foos/{id}")
    @ResponseBody
    public Foo findById(@PathVariable long id, HttpServletRequest req, HttpServletResponse res) {
        if (req.getHeader("Test") != null) {
            res.addHeader("Test", req.getHeader("Test"));
        }
        return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4));
    }
}
@Test
public void whenSendRequest_thenHeaderAdded() {
    Response response = RestAssured.get("http://localhost:8080/foos/1");
    assertEquals(200, response.getStatusCode());
    assertEquals("TestSample", response.getHeader("Test"));
}

10. Conclusion

The tutorial shows how to use Zuul to route UI requests to a REST API, solve CORS and same‑origin issues, and extend request handling with custom filters. The full Maven project is available on GitHub.

GitHub repository: https://github.com/eugenp/tutorials/tree/master/spring-zuul

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

api-gatewaySpring BootCORSSpring CloudZuulAngularJS
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.