我需要复制这个Jquery ajax功能:
$.ajax({
type: 'POST',
url: 'https://api.url.gift/api',
data: JSON.stringify({ "user_id": "100006" }),
success: function(result) {
console.log("asd");
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
},
});
哪种方法很好,但是当我在AngularJS中这样做时:
var myData = JSON.stringify({" user_id":" 100006"});
$http({
url: 'https://api.ecosquared.gift/things/cards/received_byme',
method: 'POST',
data: myData,
headers: { 'Content-Type': 'application/json; charset=UTF-8'},
}).success(function(data, status, headers, config){
console.log(data);
}).error(function(data, status, headers, config) {
console.log(data);
});
我明白了:
XMLHttpRequest cannot load https://api.url.gift/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://url.gift' is therefore not allowed access. The response had HTTP status code 405.
一个奇怪的事情,如果我不发送数据参数,请求就会变低,并且错误不会引发,但当然API不会返回我期望的数据。
有人能指出我正确的方向吗?
答案 0 :(得分:1)
尝试发送数据而不将其转换为JSON字符串且不带引号:
var myData = ({user_id: 100006 });
假设你user_id是一个整数
答案 1 :(得分:0)
无法使用Angular解决它,必须实现NodeJS并执行此操作:
request.post('https://api.url.com/api',
{body: JSON.stringify({"user_id": "222" })}, function (error, response, body) {
console.log(body);
});
然后使用AngularJS消耗它。