fix(http): 鉴权请求头改为自定义 token 头(后端联调约定,响应头 Token 同名下发)

This commit is contained in:
ozh 2026-09-16 17:07:26 +08:00
parent 87e4031fff
commit d3f9a6ae54
2 changed files with 6 additions and 6 deletions

View File

@ -61,13 +61,13 @@ export async function request<T>(
// 请求发起时刻的 token 快照:headers 注入与 401 陈旧竞态判断共用同一份 // 请求发起时刻的 token 快照:headers 注入与 401 陈旧竞态判断共用同一份
const tokenAtStart = store.getState().auth.token const tokenAtStart = store.getState().auth.token
// token 注入:从 authSlice 读取 // token 注入:后端约定自定义 token 头(无 Bearer 前缀,联调实测)
const headers: Record<string, string> = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
...config.headers ...config.headers
} }
if (config.needAuth !== false) { if (config.needAuth !== false) {
if (tokenAtStart) headers.Authorization = `Bearer ${tokenAtStart}` if (tokenAtStart) headers.token = tokenAtStart
} }
let res: Taro.request.SuccessCallbackResult<ApiEnvelope<T>> let res: Taro.request.SuccessCallbackResult<ApiEnvelope<T>>

View File

@ -103,16 +103,16 @@ describe('client envelope 解析', () => {
}) })
}) })
it('需鉴权请求注入 Bearer token 头', async () => { it('需鉴权请求注入 token 头(后端约定自定义头,无 Bearer 前缀)', async () => {
mockRequest.mockResolvedValue(okBody(null)) mockRequest.mockResolvedValue(okBody(null))
await request.get('/demo') await request.get('/demo')
expect(mockRequest.mock.calls[0][0].header.Authorization).toBe('Bearer unit-token') expect(mockRequest.mock.calls[0][0].header.token).toBe('unit-token')
}) })
it('needAuth: false 时不注入 Authorization', async () => { it('needAuth: false 时不注入 token 头', async () => {
mockRequest.mockResolvedValue(okBody(null)) mockRequest.mockResolvedValue(okBody(null))
await request.post('/demo', {}, { needAuth: false }) await request.post('/demo', {}, { needAuth: false })
expect(mockRequest.mock.calls[0][0].header.Authorization).toBeUndefined() expect(mockRequest.mock.calls[0][0].header.token).toBeUndefined()
}) })
it('BASE_URL 拼接:请求 url = BASE_URL + path', async () => { it('BASE_URL 拼接:请求 url = BASE_URL + path', async () => {