Spring boot AngularJs $http.get is empty

Dean Strydom :

I am creating a resource monitor that retrieves typical info about a machine on a different domain but same port. When accessing the url directly the data is returned successfully. However if we try it using angularJs the $http.get request would return a "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource". We decided to use the chrome CORS extension to allow the connection. Only problem is now the $http.get request is always empty despite the data existing. Not sure why this is happening as no error is produced.

Angular Controller

app.controller("ServerResourcesController", [ "$scope", "$http", function($scope, $http) {

     $http.get("http://000.000.0.0:8080/testing")
    .then(function(data){
        console.log(data);
        })
}]);

Controller

@RestController
public class ServerRestController {

    Logger logger = LoggerFactory.getLogger(ServerRestController.class);
    ServerQueryController sqc = new ServerQueryController();

    @RequestMapping("/server-service-info")
    public String ServiceInfo() {//Welcome page, non-rest
        return "Server Resource Monitor Service";
    }

    //rest end point
    @GetMapping("/server-resources-info")
    public ServerInformation ServerInformation() {
        ServerInformation serverInformation = sqc.CurrentServerResourceInformation();
        return serverInformation;
    }
    }

Object Class

@Getter @Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServerInformation {

    private String name;
    private String ipAddress;
    private double systemCpuLoad;
    private double freePhysicalMemory;
    private double totalPhysicalMemory;
    private String operatingSystem;
    private double freeDiskSpace;
    private double diskUsage;

    public ServerInformation() {

    }

    @Override
    public String toString() {
        return "Values{ systemCpuLoad: "+systemCpuLoad+
                ", freePhysicalMemory: "+freePhysicalMemory+
                ", totalPhysicalMemory: "+totalPhysicalMemory+
                ", operatingSystem: "+operatingSystem+
                ", freeDiskSpace: "+freeDiskSpace+
                ", diskUsage: "+diskUsage+
                " }";
    }

}
vancleff :

It seems your ServerRestController needs to have cross-origin, add this

@RestController
@CrossOrigin(origins = "*")
public class ServerRestController {
...
}

Also, If you want to allow a specific origin you could do it like this:

@CrossOrigin(origins = "http://stackoverflow.com", maxAge = 3600)

You can set @CrossOrigin with the origins to allow and max age either on each method or on the RestController.

Moreover, if you have multiple RestController it's not a best practice to write @CrossOrigin on each and every controller you may just create a Filter like this:

@Component
public class SimpleCORSFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

public SimpleCORSFilter() {
    log.info("SimpleCORSFilter init");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

See the example here: spring cors

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159556&siteId=1