Aurelia:配置获取客户端

Aurelia:配置获取客户端,aurelia,Aurelia,我使用Aurelia的fetch客户端与服务器通信。在使用fetch客户端的每个viewModel中,我都必须将客户端配置为使用拦截器发送自定义头(令牌) 是否有一种方法可以在某个地方配置一次fetch客户端,而不是在每个viewModel中重写拦截器代码。您可以将配置放在main.js文件中。像这样: ... aurelia.use .standardConfiguration() .developmentLogging(); let container = aurelia.cont

我使用Aurelia的fetch客户端与服务器通信。在使用fetch客户端的每个viewModel中,我都必须将客户端配置为使用拦截器发送自定义头(令牌)


是否有一种方法可以在某个地方配置一次fetch客户端,而不是在每个viewModel中重写拦截器代码。

您可以将配置放在main.js文件中。像这样:

...
aurelia.use
  .standardConfiguration()
  .developmentLogging();

let container = aurelia.container;

let http = new HttpClient();
http.configure(config => {
  config
  .useStandardConfiguration()
  .withBaseUrl('http://localhost:8080/api/')
  .withDefaults({
     headers: {
       'Authorization': tokenVariable // <---- your magic here
     }
  })
  .withInterceptor({
    request(request) {
      console.log(`Requesting ${request.method} ${request.url}`);
      return request;
    },
    response(response) {
      console.log(`Received ${response.status} ${response.url}`);
    }
  });
});

container.registerInstance(HttpClient, http);

有关详细信息,请参见

如何为每个特定url配置api url?不必为每个调用配置整个url。您可以配置基本url,例如
http://localhost:8080/api/
。然后,您只需调用
this.http.fetch('something')
。最终的URL将是->
http://localhost:8080/api/something
我对其进行了测试,但出现了一个错误“HttpClient”未定义。然后我添加了“import{HttpClient}from'aurelia fetch client'”,但现在的错误是“TypeError:window.localStorpassword未定义”。我使用它从本地存储获取令牌。您应该编写一个函数来检查localStorageProperty是否未定义。类似于
if(window.localStorage.token!==未定义)
@inject(HttpClient)
export class MyViewModel {
}