You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用TypeScript JsonServiceClient的BasicAuth回退机制?

解决TypeScript JsonServiceClient禁用BasicAuth回退机制的方案

要搞定TypeScript版JsonServiceClient禁用BasicAuth自动回退重试的问题(就是不让它在收到401后自动重发带凭证的请求),同时只在特定端点用BasicAuth,有几个实用的方法:

1. 全局关掉自动重试逻辑

直接把客户端的autoRetryUnauthorized属性设为false,这样客户端收到401时就不会自动重试了:

import { JsonServiceClient } from '@servicestack/client';

const client = new JsonServiceClient('/api');
client.autoRetryUnauthorized = false; // 禁用401自动重试机制

2. 给特定请求手动加BasicAuth凭证

既然只需要在特定端点用BasicAuth,那就发起这些请求时手动带上Authorization头,不用依赖客户端的自动回退:

// 生成BasicAuth凭证的工具函数
function getBasicAuthHeader(username: string, password: string) {
    const credentials = btoa(`${username}:${password}`);
    return `Basic ${credentials}`;
}

// 针对特定请求添加凭证
const response = await client.post(new MySecureRequest(), {
    headers: {
        'Authorization': getBasicAuthHeader('你的用户名', '你的密码')
    }
});

3. 用请求过滤器精准控制

如果需要更灵活的规则(比如根据请求URL或者请求类型来判断),可以加个请求过滤器,配合全局禁用自动重试,只给指定请求加凭证:

client.autoRetryUnauthorized = false;

client.requestFilter = (req) => {
    // 这里可以根据请求URL或者请求类型来判断
    if (req.url.includes('/需要验证的端点') || req.body instanceof 你的安全请求类型) {
        req.headers.set('Authorization', getBasicAuthHeader('你的用户名', '你的密码'));
    }
};

这样设置后,客户端不会再自动发两次请求,只会在你指定的请求上主动携带BasicAuth凭证,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Barry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 22:54:55