使用 $http POST 内容类型 application/x-www-form-urlencoded 访问 API
Accessing API with $http POST Content-Type application/x-www-form-urlencoded
我正在尝试访问此 REST API,它接受三个参数:
stationId
、crusherId
、monthYear
我在 AngularJS 中是这样做的:
$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);
})
但我总是这样:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
或
{"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'},
它给出:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
或
{"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":""}
我做错了什么,请帮助我。
Plunker 在这里:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(编辑)
注:
我可以在 jQuery
中做到这一点:
<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”的百万为:26862094万
太完美了。 :)
The documentation 表示 stationId 和 crusherId 参数应该是字符串数组。此外,您似乎正在发送 JSON 数据,因此请务必正确设置 header。
$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'
}
})
当我更改您的 plunkr 中的代码以使用上面更正后的代码时,我得到以下响应:“请求的资源不支持 http 方法 'OPTIONS'。
正如正确提到的另一个(现已删除)答案,这意味着存在 CORS 问题。浏览器试图在发出 cross-origin 请求之前发送 "preflight" 请求,而服务器不知道如何处理它。您还可以在 Chrome 控制台中看到此消息:
XMLHttpRequest cannot load
https://fnrc.gov.ae/roayaservices/api/getHPData. Response for
preflight has invalid HTTP status code 405
发布经过 URL 编码的表单数据时,使用 $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
函数解决了这个问题。
我正在尝试访问此 REST API,它接受三个参数:
stationId
、crusherId
、monthYear
我在 AngularJS 中是这样做的:
$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);
})
但我总是这样:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
或
{"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'},
它给出:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
或
{"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":""}
我做错了什么,请帮助我。
Plunker 在这里:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(编辑)
注:
我可以在 jQuery
中做到这一点:
<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”的百万为:26862094万
太完美了。 :)
The documentation 表示 stationId 和 crusherId 参数应该是字符串数组。此外,您似乎正在发送 JSON 数据,因此请务必正确设置 header。
$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'
}
})
当我更改您的 plunkr 中的代码以使用上面更正后的代码时,我得到以下响应:“请求的资源不支持 http 方法 'OPTIONS'。
正如正确提到的另一个(现已删除)答案,这意味着存在 CORS 问题。浏览器试图在发出 cross-origin 请求之前发送 "preflight" 请求,而服务器不知道如何处理它。您还可以在 Chrome 控制台中看到此消息:
XMLHttpRequest cannot load https://fnrc.gov.ae/roayaservices/api/getHPData. Response for preflight has invalid HTTP status code 405
发布经过 URL 编码的表单数据时,使用 $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
函数解决了这个问题。