Angular $http POST 400 错误请求时无法得到响应
Angular $http POST cannot get response when 400 bad request
前端代码 POST 用户凭证到后端,如果凭证无效,则后端服务器响应 400 错误请求 和响应以下数据
{
"error": "invalid_grant",
"error_description": "Invalid username or password"
}
我在浏览器的网络选项卡和邮递员 chrome 应用程序中看到了这个响应。
出于某种原因,我无法获得此响应或捕获错误或错误状态。请在下面找到我的代码片段
newLoginAuth: function(credentials) {
var deferred = $q.defer();
$http({
url: 'https://myserver.com/api/connect/token',
method: "POST",
data: {
'username': credentials.username,
'password': credentials.password,
'clientId': 'clientId',
'clientSecret': 'Y2xpZW50U2VjcmV0'
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
})
.then(function(response) {
deferred.resolve(response);
}, function(response) {
deferred.reject(response);
});
return deferred.promise;
}
myService.newLoginAuth({username: self.userName, password: self.password})
.then((result) => {
console.log(result); //undefined
});
有人可以帮助我吗?我是不是做错了什么?
响应对象具有以下属性:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
if(response.status == 400) alert('Bad Request');
前端代码 POST 用户凭证到后端,如果凭证无效,则后端服务器响应 400 错误请求 和响应以下数据
{
"error": "invalid_grant",
"error_description": "Invalid username or password"
}
我在浏览器的网络选项卡和邮递员 chrome 应用程序中看到了这个响应。
出于某种原因,我无法获得此响应或捕获错误或错误状态。请在下面找到我的代码片段
newLoginAuth: function(credentials) {
var deferred = $q.defer();
$http({
url: 'https://myserver.com/api/connect/token',
method: "POST",
data: {
'username': credentials.username,
'password': credentials.password,
'clientId': 'clientId',
'clientSecret': 'Y2xpZW50U2VjcmV0'
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
})
.then(function(response) {
deferred.resolve(response);
}, function(response) {
deferred.reject(response);
});
return deferred.promise;
}
myService.newLoginAuth({username: self.userName, password: self.password})
.then((result) => {
console.log(result); //undefined
});
有人可以帮助我吗?我是不是做错了什么?
响应对象具有以下属性:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
if(response.status == 400) alert('Bad Request');