Pergunta

I've got an example app: https://github.com/LateralThoughts/orsyp-frontend-training/tree/master/zupr_trackr. It exposes 3 JPA entities (Company, Employee, Activity) via REST resources handled by Spring DATA/REST.

Although I can successfully query the REST API through a browser REST add-on for instance, the following query (on the same domain or another one) always returns a 404:

$.getJSON("http://localhost:8080/api/companies/")
    .success(function() { alert("success"); })
    .fail(function(event, jqxhr, exception) {
        console.log(jqxhr, exception);
    })
    .complete(function() { alert("Done"); }
);

The only difference we noticed while comparing a generated HTTP request (via a REST add-on) and a jquery-driven one is the absence of 'Referer' in the first case and its presence in the last.

Adding this header with the REST add-on interface will cause the request to fail as described earlier.

Any ideas are welcome, thanks in advance

Rolf

P.S.: this is true for GET/POST and other verbs.

Foi útil?

Solução

Spring Data REST doesn't like the Accept headers sent by jQuery.

jQuery sends these headers :

Accept:application/json, text/javascript, */*; q=0.01

And if you try queries like this :

curl -v -XGET -H "Accept:application/json, text/javascript, */*; q=0.01" http://localhost:8080/api/employees/

it will fail as a 404, but if you change it by removing the text/javascript part :

curl -v -XGET -H "Accept:application/json, */*; q=0.01" http://localhost:8080/api/employees/

this one works.

You can override the default Accept headers used by jQuery by using the $.ajaxSetup method, or you can simply override these settings when you query your API.

$.ajax({
    url : "http://localhost:8080/api/employees", 
    accepts: {json:'application/json'}
})

Now about the why, I think there's a problem in Spring Data REST here :

https://github.com/SpringSource/spring-data-rest/blob/master/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/RepositoryRestHandlerMapping.java#L46

where the Accept header is matched, and I think it may be due to the fact that text/javascript doesn't exists for SpringData REST.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top