Home > Back-end >  How to configure springboot to allow make requests from ip 10.0.2.2
How to configure springboot to allow make requests from ip 10.0.2.2

Time:12-30

I want to test my angular app on virtual MacOS but the problem is that I use 10.0.2.2 ip to connect to the ressources. What should I do in in my springboot app to be able to access and from localhost and from 10.0.2.2?

CodePudding user response:

You have two options:

1) Let the Angular dev server proxy your backend requests to your backend

You need to create a file proxy.conf.json and reference it in your angular.json file:

        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            ...
       --> "proxyConfig": "proxy.conf.json" <-- 
          },
          ...
        }

In your proxy.conf.json you define which paths you want to proxy to which host. Let's say your API requests are all prefixed with /api and your Spring backend is running on port 1234 you'd need the following config:

{
  "/api/*": {
    "target": "http://localhost:1234",
    "secure": false
  }
}

You then need to make sure, that your requests in the development mode are only relative and do not include the hostname. You can achieve that by having a key called BACKEND_URL in your environment.ts which is an empty string in development and the actual URL in the environment.prod.ts. You then need to use that key in your services that make calls to your backend.

More information can be found in the official Angular docs.

2) Set the @CrossOrigin annotation on your controllers / controller endpoints

You can directly specify which hosts should be allowed to access your endpoints. As you need to achieve this only for testing / development purposes, I suggest that you stick to the first method so that you don't have development related code in your production code.

Example from a Spring guide adapted to your IP address:

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";

    private final AtomicLong counter = new AtomicLong();

    @CrossOrigin(origins = "10.0.2.2")
    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(required = false, defaultValue = "World") String name) {
        System.out.println("==== get greeting ====");
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }

}

Here a Baeldung article on this topic and of course the official Spring reference.

  • Related