简体   繁体   中英

How to send a rest PUT request in angular passing body

I need to send a rest request to a web server, I am using this code :

var getData = function(...) {
    return $http({
      method: "PUT",
      url: getStatistics,
      headers: {
        'loginId': ...,
        'token': ...,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {"...":"...","...":"...","...":"...","...":"...",
             "...":"....","....":"...",
             "datefrom":"2017-01-01","dateto":"2017-10-20"}
    }).then(function(result){
        var dataString = JSON.stringify(result.data);
        alert(result.data);
        return result.data;
    });
};

The problem is that I am receiving error 400 bad request, What should I do?

The request works on Postman With this structure

https://i.stack.imgur.com/BBrwF.jpg

https://i.stack.imgur.com/NbQuO.jpg

Should it be a problem of how Am I passing the data object ?

That's how I implemented the $httpParamSerializerJQLike, it it Correct?

app.factory('statistics', function($http,$httpParamSerializerJQLike) {
var getData = function(loginId,token,id,dataInizio,dataFine,periodo,selezione) {
    // Angular $http() and then() both return promises themselves

    var data = '{"datefrom":"2017-01-01","dateto":"2017-10-20"}';

    alert(data);
    return $http({
      method: "PUT",
      url: getStatistics,
      headers: {
        'loginId': loginId,
        'token': token,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: { 'data': $httpParamSerializerJQLike(data)}
    }).then(function(result){
        var dataString = JSON.stringify(result.data);
        alert(result.data);
        return result.data;
    });
};

return { getData: getData };
});

you're sending an x-www-form-urlencoded body, but it contains a single parameter named data, containing JSON.

You thus need

data: $httpParamSerializerJQLike({data: angular.toJson(data)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM