Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

angularjs - Angular, content type is not being generated correctly when using resource

I have tried the following command, using resource on Angular:

angular.module('appServices', ['ngResource']).factory('Example', 
        function($resource){

            return $resource('http://api.example.com.br/teste', {}, {
                query: {method:'GET', headers: {'Content-Type': 'application/json'}}
        });
});

but the http content type is not being generated correctly, in this case "application/json".

I have seen similar questions like AngularJS resource not setting Content-Type ,but I have the lastest Angular version (1.0.6/1.1.4).

What is wrong with the code above?

Conclusion

  • As mentioned bellow, HTTP Get method should not have a body.
  • The attribute headers does not work in the version described above. I used the following command unsuccessfully: query: {method:'POST', headers: {'Content-Type': 'application/json'}}
  • This way has worked for me: $http.defaults.headers.put['Content-Type'] = 'application/json';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Look at the angular source, line 8742 in the version 1.1.4:

  // strip content-type if data is undefined
  if (isUndefined(config.data)) {
    delete reqHeaders['Content-Type'];
  }

The Content-Type header gets removed if the request does not contain any data (a request body).

I think this is the expected behaviour since GET requests do not have a body.

A POST method in the other hand, will set the content-type as you expect, as long it has data in the request body. Try the following:

Change the method to POST

query: {method:'POST', headers: {'Content-Type': 'application/json'}}

And call your resource action with some parameter:

Example.query(yourData)

In this case the content type is correctly set.

Edit:

It seems it also works with get, in this case the data is in the second parameter:

Example.query(yourParams, yourData)

An example: http://jsfiddle.net/WkFHH/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...