我正在学习AngularJs并且我试图编写一个非常基本的脚本向Ebay公共API发送http请求,我已经注册并获得了我的API密钥,我已经多次阅读了文档并写了这个基本代码:
$scope.getQueryUrl = function () {
// Some unrelated code ...
$scope.queryUrl["Ebay"] = "http://svcs.sandbox.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-NAME=FindingService&SERVICE-VERSION=1.0.0&GLOBAL-ID=EBAY-US&SECURITY-APPNAME="+dataAuth.EbayKeyApi+"&RESPONSE-DATA-FORMAT=XML&keywords="+$scope.qtext ;
};
$scope.sendRequest = function () {
$scope.getQueryUrl(); // Gets the query url after adding all the parameters
alert($scope.queryUrl.Ebay);
$http.get($scope.queryUrl["Ebay"]).then(
function(response){
alert("success" + response.data );
},
function(response){
alert("error" + response.statusCode );
});
};
此代码的工作原理:
它应该创建一个格式化的Ebay查询URL,通过HTTP GET请求发送它并发回响应。
注意:$scope.qtext
&已为dataAuth.EbayKeyApi
分配了各自的值。
问题是什么:
问题是使用此Angularjs脚本时,代码不起作用,显示警告“错误”,并且response.statusCode
未定义。
但是当我在Firefox中复制格式化的Ebay查询链接时,它可以很好地工作并显示XML响应。
使用提供的脚本生成格式化的Ebay查询。
我认为这是与标题相关的问题。
答案 0 :(得分:0)
$ http定义了一些默认标头。 $ http默认发送Json有效负载并接受Json作为响应。由于您正在处理XML,因此必须使用标头将接受的响应类型显式指定为XML: 接受:application / xml
请使用以下函数和相应的标题,您应该得到回复。另外,请查看ebay API上的任何跨源资源共享(CORS)限制。
function getRequest(url) {
$http({
method: "GET",
url: url,
headers: {
'Content-Type': 'application/xml, text/xml',
'Accept': 'application/xml, text/plain, * / *'
}
})
.then(function (response) {
alert(response.data);
},
function (error) {
alert (error);
});
}
谢谢你, 索马。