首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用$http POST内容访问API -Type应用程序/x-www-form-urlencoded

使用$http POST内容访问API -Type应用程序/x-www-form-urlencoded
EN

Stack Overflow用户
提问于 2017-04-25 13:21:08
回答 2查看 5.3K关注 0票数 1

我试图访问这个REST,它接受三个参数:stationIdcrusherIdmonthYear --我在AngularJS中这样做是为了:

代码语言:javascript
复制
$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);
        })

但我总能明白这一点:

对象{数据:“{”结果:“false”},状态: 200,配置:对象,statusText:“确定”,标头:函数}

{“数据”:“{\”结果\“\”“false\”},“状态”:200,“配置”:{“方法”:“POST”,"transformRequest":null,"transformResponse":null,transformRequestcharset=utf-8,“接受”:“application/json”},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,“monthYear”:“2016-4”},"statusText":"OK"}

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

代码语言:javascript
复制
headers: {'Content-Type': 'application/json; charset=UTF-8'},

它规定:

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

{“数据”:空,“状态”:-1,“配置”:{“方法”:“POST”,"transformRequest":null,"transformResponse":null,“headers”:{“Content”:“application/json”;charset=utf-8,“接受”:“application/json,text/平原,/"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,”monthYear“:”2016-4“},”statusText“:”}

我做错了什么,请帮帮我。

普塞克在这里:

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

(编辑)

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

代码语言:javascript
复制
<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"}
  • 完成加载: POST "https://myurl../api/getHPData“。
  • foo的日志是: 26862094
  • "26862094“百万是:26862.094亿

这太完美了。:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-25 15:34:13

当发布经过URL编码的表单数据时,使用$httpParamSerializer服务转换请求

代码语言:javascript
复制
$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函数解决了这个问题。

The PLNKR演示

票数 4
EN

Stack Overflow用户

发布于 2017-04-25 13:32:23

文献资料说,stationId和crusherId参数应该是字符串数组。而且,看起来您正在发送JSON数据,所以请确保正确设置该头。

代码语言:javascript
复制
$http({
    headers: {
        'Content-Type': 'application/json', 
        'Accept':       'application/json'
    },
    url:    'https://fnrc.gov.ae/roayaservices/api/getHPData',
    method: 'POST',
    data: {
        stationId: ['263'], 
        crusherId: ['27'], 
        monthYear: '2016-4'
    }
})

当我将柱塞中的代码更改为使用上面更正的代码时,我会得到以下响应:“请求的资源不支持http方法‘选项’。”

正如另一个(现在删除的)答案正确提到的,这意味着存在一个CORS问题。浏览器试图在发出跨源请求之前发送“预飞”请求,而服务器不知道如何处理它。您还可以在Chrome控制台中看到此消息:

XMLHttpRequest无法加载https://fnrc.gov.ae/roayaservices/api/getHPData。航班前响应有无效的HTTP状态代码405

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43611892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档