使用$ http POST Content-Type应用程序/x-www-form-urlencoded访问API [英] Accessing API with $http POST Content-Type application/x-www-form-urlencoded

查看:120
本文介绍了使用$ http POST Content-Type应用程序/x-www-form-urlencoded访问API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问此REST API,该API接受三个参数: stationIdcrusherIdmonthYear 我在AngularJS中这样做是这样的:

I am trying to access this REST API, which accepts three parameters: stationId, crusherId, monthYear I am doing it like this in AngularJS as:

$http({
        //headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
        //headers: {'Content-Type': 'application/json; charset=UTF-8'},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
            'Accept':       'application/json'
        },
        url:    'https://myurl../api/getHPData',
        method: 'POST',
        data: {
            stationId: 263, 
            crusherId: 27, 
            monthYear: '2016-4'
        }
    })

    .then(function(data, status, headers, config) {
            //console.log(JSON.stringify(response));
            console.log(data);
     })
    .catch(function(error){
            //console.log("Error: " + JSON.stringify(error));
            console.log(error);
        })

但是我总是得到这个:

对象{data:"{" result:" false}",状态:200,配置:Object,statusText:"OK",标头:function}

Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}

OR

{"data":"{\" result \:\" false \}","status":200,"config":{"method":"POST","transformRequest":[null] ,"transformResponse":[空],标题":{"Content-Type":"application/x-www-form-urlencoded; charset = UTF-8," Accept:" application/json}," url:" https://myurl../api/getHPData ," data:{" stationId:263," crusherId:27," monthYear:" 2016-4}}," statusText:" OK"}

{"data":"{\"result\":\"false\"}","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":"OK"}

如果我将header Content-Type更改为:

headers: {'Content-Type': 'application/json; charset=UTF-8'},

它给出:

对象{数据:空,状态:-1,配置:对象,statusText:",标题:函数}

Object {data: null, status: -1, config: Object, statusText: "",headers: function}

OR

{数据":空,状态":-1,配置":{方法":"POST","transformRequest":[空],"transformResponse":[空],标题": {"Content-Type":"application/json; charset = UTF-8," Accept:" application/json,text/plain, /}," url:" https://myurl../api/getHPData ," data:{" stationId:263," crusherId:27," monthYear:" 2016-4}}," statusText:"}

{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/json; charset=UTF-8","Accept":"application/json, text/plain, /"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":""}

我做错了,请帮助我.

What I am doing wrong, Please help me.

柱塞在这里:

https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview

(编辑)

注意: 我可以在jQuery中这样做:

Note: I can do it in jQuery as:

<script>
$(document).ready(function() {
        get_homepage_data(263, 27, '2016-04');

        function get_homepage_data(stationIds, crusherIds, date) {
            var url = "https://myurl../api/getHPData";
            var data_to_send = {
                'stationId': stationIds, 
                'crusherId': crusherIds,
                'monthYear': date
            };

            console.log("Value is: " + JSON.stringify(data_to_send));
            //change sender name with account holder name
            //        console.log(data_to_send)
            $.ajax({
                url: url,
                method:   'post',
                dataType: 'json',
                //contentType: 'application/json',
                data: data_to_send,
                processData: true,
                // crossDomain: true,
                beforeSend: function () {
                }
                , complete: function () {}
                , success: function (result1) {
                    var Result = JSON.parse(result1);
                    var value_data = Result["valueResult"];
                    var foo = value_data["gyydt"];

                    console.log("Log of foo is: " + foo);

                    var foo2 = 0;
                    // 10 lac is one million.
                    foo2 = foo / 1000000 + ' million';

                    console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
                }
                , error: function (request, error) {
                    return false;
                }
            });
        }   
    }); // eof Document. Ready  
</script>

上述脚本的输出为script是:

  • 值是:{"stationId":263,"crusherId":27,"monthYear":"2016-04"}
  • XHR已完成加载:POST " https://myurl../api/getHPData ".
  • foo的日志是:26862094
  • "26862094"(以百万为单位)是:26862.94万
  • Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
  • XHR finished loading: POST "https://myurl../api/getHPData".
  • Log of foo is: 26862094
  • "26862094" in million is: 26.862094 million

这是完美的. :)

推荐答案

发布URL编码的表单数据时,请使用

When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:

$http({
    headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
    url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
    method: 'POST',
    transformRequest: $httpParamSerializer,
    transformResponse: function (x) {
      return angular.fromJson(angular.fromJson(x));
    },
    data: {
      "stationId": 263,
      "crusherId": 27,
      "monthYear": '2016-04'
    }
}) 
  .then(function(response) {
    console.log(response);
    $scope.res = response.data;
    console.log($scope.res);
});

通常$ http服务会自动解析JSON编码对象的结果,但是此API返回的是已从对象进行双重序列化的字符串. transformResponse函数可解决该问题.

Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.

在PLNKR上进行演示

这篇关于使用$ http POST Content-Type应用程序/x-www-form-urlencoded访问API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆