Aurelia 授权响应

Aurelia auth response

我正在使用 aurelia 身份验证进行登录。但是我无法从服务器获取错误消息。在 catch 方法中 err.response 未定义。 Err 是主体类型为可读流的对象。下面是我的代码:

this.auth.login(bodyContent)
  .then(response=>{
  })
  .catch(err=>{
    console.log(err);
    console.log(err.response);
  });

在 chrome 开发者工具中我可以看到响应消息。 这是错误打印:

我在这里 (https://gist.github.com/bryanrsmith/14caed2015b9c54e70c3) 找到了解决方案,如下所示:

.catch(error => error.json().then(serverError =>
  console.log(serverError) 
}));

可以在 Aurelia 文档中找到解释:

The Fetch API has no convenient way of sending JSON in the body of a request. Objects must be manually serialized to JSON, and the Content-Type header set appropriately. aurelia-fetch-client includes a helper called json for this.

我最近也遇到了同样的问题。

我最终创建了一个名为 FetchError 的 class 来封装这些类型的错误。然后,只要在获取过程中发生错误,我就会抛出 FetchError。

login.ts:

import { FetchError } from '../../errors';

  login() {
    var credentials = { grant_type: "password", username: this.username, password: this.password };
    return this.auth.login(credentials, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
      .then((response) => {
        return this.auth;
      }).catch(err => {
        this.errorMessage = "Login failed";
        throw new FetchError("Unable to log in", err);
      });
  };

FetchError class 使用 'http-status-codes' 节点模块查找文本描述。

errors.ts:

import * as HttpStatus from 'http-status-codes';

export class BaseError extends Error {
  constructor(message) {
    super(message);
    this.message = message;
  }
}

export class FetchError extends BaseError {
  statusCode: number;
  statusText: string;
  description: string;

  constructor(message: string, err: any) {
    super(message);

    if (err instanceof Response) {
      var resp = <Response>err;
      this.statusCode = resp.status;

      if (resp.status == 12029)
        this.statusText = "A connection to server could not be established";
      else
        this.statusText = HttpStatus.getStatusText(resp.status);

      resp.json()
        .then(body => {
          this.description = body.Message;
          console.log(`Error: ${this.message}, Status: ${this.statusText}, Code: ${this.statusCode}, Description: ${this.description}`);
        })
    }
    else if (err instanceof Error) {
      var error = <Error>error;
      this.description = err.message;
      console.log(`Error: ${this.message}, Description: ${this.description}`);
    }
    else {
      this.description = "???";
      console.log(`Unknown error: ${this.message}`);
    }
  }
}

我相信有更好的方法可以做到这一点。我还在思考这个问题。