Search code examples
angularspring-bootspring-mvcapache-httpclient-4.xhttp-proxy

Getting 404 error when connecting angular proxy config with spring mvc


Am trying to connect angular with spring mvc using proxy json. i have tried multiple attempts, but always throwing 404 error.

GET http://localhost:4200/api/v1/employees 404 (Not Found)

Here is the snippet of my code block. Thanks in advance.

proxy.conf.json

{
    "/api/v1": {
      "target": "http://localhost:8080",
      "secure": false,
      "changeOrigin": true
    }
  }

app.component.ts

getAllEmployees() {
    this._http.get('/api/v1/employees').subscribe(
      data => {
        this.result = data.toString();
      },
      error => {
      });
}

controller

@RestController
@RequestMapping(value = "/api/v1")
public class HomeController {
    @RequestMapping("/employees")
    public String getDisplayMessage() {
        return "Hi Welcome!!!";
    }   
}

web.xml

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Assume getAllEmployee() method called when clicking html button.

I can get message "Hi Welcome!!!" , when i try http://localhost:8080/spring-mvc-demo/api/v1/employees

Can someone tell me where did i coded wrong?


Solution

  • see the inconsistency: your code does a request to /api/v1/employees witch is proxied to (we just prepend http://localhost:8080) http://localhost:8080/api/v1/employees and in your api as you said path http://localhost:8080/spring-mvc-demo/api/v1/employees is expected. I believe your proxy should be

    {
        "/api/v1": {
          "target": "http://localhost:8080/spring-mvc-demo",
          "secure": false,
          "changeOrigin": true
        }
      }