我见过类似的事件,例如this https://stackoverflow.com/questions/32132171/convert-ajax-call-to-angularjs-http-post。然而,他们似乎都没有遇到我遇到的同样问题:发出 POST 请求并获取500 Internal Server Error
作为回应。
我正在尝试转换以下任一内容AJAX
or XHR
我从 postman 命令生成到使用 AngularJS 方法$http
服务:
The xhr:
var data = "json=<lots of encoded text>";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic <auth data>");
xhr.send(data);
阿贾克斯:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"authorization": "Basic <auth data>"
},
"data": {
"json": "<raw json text>"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
损坏的 AngularJS 实现:
var heads = new Headers();
heads.append('Content-Type', 'application/x-www-form-urlencoded');
heads.append('Authorization', 'Basic <auth data>');
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: <json object>,
headers: heads
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
上述 Ajax 和 xhr 实现都可以正常工作。如上所述,角度方法给我一个 500 内部服务器错误。
任何想法为什么会发生这种情况?如果有帮助的话,我可以提供具体信息,例如 chrome 检查器上的网络选项卡中的信息。请告诉我应该截取哪些内容,我会将其发布到此处。
编辑:正如评论中所承诺的,我的解决方案如下。
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: 'json=' + JSON.stringify(data),
headers: {
'Accept': "*/*",
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic <auth data>'
}
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
编辑2:如果你偶然发现这个问题,因为你也得到了500 Internal Server Error
并且仍然不明白这是如何解决的,然后通过确保在包含端点的服务器上设置 CORS 的组合来解决这个问题(由 Crome 的检查员抛出Access-Control-*
错误)以及正确格式化 x-www-form-urlencoded 以便 Jenkins 接受,这要求发送的数据采用以下形式json={"parameter":[{"name":<key>, "value":<value>}, ...]}
。此外,如果value
条目是嵌套的,则需要转义。看这个答案 https://stackoverflow.com/a/46330078/5812876更多细节。