Pergunta

I am trying to do a an HTTP POST to a server.

The data I have to send is a json object.

The problem is that $http.post in angular override the method with options.

I can make this config

.config(['$httpProvider', function ($httpProvider) {
  //Reset headers to avoid OPTIONS request (aka preflight)
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
}])

and changes from options to POST, but I can't set the content-type to "application/json", and I am getting a "415 Unsupported Media Type"

Thank you

Foi útil?

Solução

$http.post in angular doesn't override the method with OPTIONS. It appear that you are trying to call api in different domain than the one your JS code come from. This is called Cross Domain. For such cases the browser performs preflight request with OPTIONS in order to see the returned headers. In your backend response you should add the header Access-Control-Allow-Origin: * for example. When the browser sees that header he performs the actual POST request.

More details here: https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS

Hope this is helps!

Outras dicas

Add

$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';

But note this will set the Content-Type header globally.

If you need to set the content-type per call, you should use $http.post like

 $http.post("/foo/bar", requestData, {
        headers: { 'Content-Type': 'application/json'},
        transformRequest: transform
    }).success(function(responseData) {
        //do stuff with response
    });
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top