当400错误请求时,Angular $ http POST无法获得响应

时间:2017-02-05 04:25:09

标签: angularjs http promise http-post http-status-code-400

前端代码将用户凭据POST到后端,如果凭据无效,则后端服务器响应 400错误请求,并在下面显示响应数据

{
  "error": "invalid_grant",
  "error_description": "Invalid username or password"
}

我在浏览器的网络标签中以及postman chrome app中看到此响应。

由于某种原因,我无法获得此响应或捕获错误或错误状态。请在下面找到我的代码片段

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
          });

有人能帮助我吗?我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

响应对象具有以下属性:

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');