Serhii Shevchyk
Serhii Shevchyk

Reputation: 39436

Spring RESTfull Web Service + AngularJS HTTP 404 error

I'm trying to consume webservice on my local machine and use AngularJS $http. Via browser everything works fine and I receive correct JSON response. But with AngularJS $http I receive 404 error, however, handler is found and response is being generated.

FrontEnd:

$http.get('http://localhost:8080/apartments.json').
            success(function(data){
                $scope.apartments = data;
            }).
            error(function(data, status){
                alert("Error "+ status);
            });

BackEnd:

@Controller
public class ApartmentsController {

    @RequestMapping(value = "/apartments", method = RequestMethod.GET)
    public @ResponseBody List<ApartmentEntity> getAll(){
        ApartmentEntity apartmentEntity = new ApartmentEntity();
        apartmentEntity.setName("test");
        apartmentEntity.setPrice(1000);
        return Arrays.asList(apartmentEntity);
    }
}

Servlet is mapped correctly.

Could you please suggest what is wrong?

Upvotes: 0

Views: 1873

Answers (1)

Angular University
Angular University

Reputation: 43087

The problem is that Angular is by default trying to use CORS as this is an ajax request attempt from one page loaded from one server to a REST service running in another server.

The way it tries to use CORS is by issuing the GET with a default header that triggers the browser to do a 'pre-flight' OPTIONSrequest.

This pre-flight automatic OPTIONS request is for the browser to get the list of supported methods by the server, and this is the first step of CORS.

So the 404 comes from this OPTIONS request.

See this issue in Angular, it seems that this was fixed in more recent versions as it was causing a lot of questions from users. See also the original issue that triggered the fix.

In you case for local development you can always deploy both applications in the same server and the problem is solved.

If in production it's necessary to run frontend/backend on separate servers, then either proxy those servers by a common frontend server like nginx/Apache or or turn on CORS, see enable-cors.org.

Upvotes: 1

Related Questions