From 57c9524f346117feb13fb7523927582e2f0fbb70 Mon Sep 17 00:00:00 2001 From: chenos Date: Wed, 23 Feb 2022 18:20:45 +0800 Subject: [PATCH] feat(client): add the setBearerToken method to the APIClient --- packages/app/src/pages/apiClient.ts | 2 ++ packages/client/src/api-client/APIClient.ts | 12 +++++++++++- packages/client/src/api-client/demos/demo1.tsx | 4 ++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/app/src/pages/apiClient.ts b/packages/app/src/pages/apiClient.ts index 105a0033bc..0ebbabb0ae 100644 --- a/packages/app/src/pages/apiClient.ts +++ b/packages/app/src/pages/apiClient.ts @@ -4,6 +4,8 @@ const apiClient = new APIClient({ baseURL: `http://localhost:3000/api/`, }); +apiClient.setBearerToken(); + // mock(apiClient); export default apiClient; diff --git a/packages/client/src/api-client/APIClient.ts b/packages/client/src/api-client/APIClient.ts index d36234987d..6fa285a122 100644 --- a/packages/client/src/api-client/APIClient.ts +++ b/packages/client/src/api-client/APIClient.ts @@ -37,6 +37,16 @@ export class APIClient { } } + setBearerToken(key = 'nocobaseToken') { + this.axios.interceptors.request.use((config) => { + const token = localStorage.getItem(key); + if (token) { + config.headers['Authorization'] = `Bearer ${token}`; + } + return config; + }); + } + service(uid: string): Result { return this.services[uid]; } @@ -74,4 +84,4 @@ export class APIClient { }; return new Proxy(target, handler); } -} \ No newline at end of file +} diff --git a/packages/client/src/api-client/demos/demo1.tsx b/packages/client/src/api-client/demos/demo1.tsx index aab4a16f7a..6c4f3bb8f8 100644 --- a/packages/client/src/api-client/demos/demo1.tsx +++ b/packages/client/src/api-client/demos/demo1.tsx @@ -1,6 +1,6 @@ -import React from 'react'; +import { APIClient, APIClientProvider, compose, useRequest } from '@nocobase/client'; import MockAdapter from 'axios-mock-adapter'; -import { APIClient, APIClientProvider, useRequest, compose } from '@nocobase/client'; +import React from 'react'; const apiClient = new APIClient();