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

tus-js-client中POST请求Authorization头缺失的原因排查

问题原因与解决方案

核心原因

出现POST请求未携带Authorization头并返回401的问题,本质是跨域请求的CORS配置不完整:浏览器在处理带自定义头(如Authorization)的跨域请求时,会先发送OPTIONS预检请求,只有当服务器明确返回允许携带该自定义头、允许Credentials的响应后,浏览器才会在后续的POST请求中携带这些头信息。你的当前配置缺少这部分关键的CORS授权。


具体修复步骤

1. 完善Spring Cloud Gateway的CORS全局配置

在Gateway配置中添加CORS过滤器,明确允许自定义头、跨域凭证以及tus协议所需的特殊头:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "http://mydomain" # 替换为你的前端实际域名
            allowedMethods: "*"
            allowedHeaders: "Authorization,Tus-Resumable,Upload-Length,Upload-Metadata"
            allowCredentials: true
            maxAge: 3600

如果只需要针对tusd路由配置,也可以在路由的filters中添加CORS规则,替代全局配置。

2. 调整tus-js-client的客户端配置

在Upload实例中添加withCredentials参数,并显式指定tus协议版本头,确保浏览器正确携带凭证和自定义头:

let upload = new tus.Upload(file, {
    endpoint: "http://mydomain/files/addressfull",
    withCredentials: true, // 开启跨域凭证携带
    headers: {
        "Authorization": `Bearer ${keycloak.token}`,
        "Tus-Resumable": "1.0.0" // 显式声明tus协议版本,避免预检不兼容
    },
    retryDelays: [0, 3000, 5000, 10000, 20000],
    metadata: {
        filename: file.name,
        filetype: file.type,
        test: "test"
    },
    onError: function(error) {
        console.log("Failed because: " + error)
    },
    onProgress: function(bytesUploaded, bytesTotal) {
        let percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
        console.log(bytesUploaded, bytesTotal, percentage + "%")
    },
    onSuccess: function() {
        console.log("Download %s from %s", upload.file.name, upload.url)
    }
})

3. 补充tusd的CORS启动参数(可选,双重保险)

在tusd的Docker启动命令中添加CORS相关参数,确保服务本身也能正确响应预检请求:

command: ["-s3-endpoint=${S3_ENDPONINT}", "-s3-bucket=addressfull", "-base-path=/files/addressfull", "-cors-allowed-origins=http://mydomain", "-cors-allowed-headers=Authorization,Tus-Resumable,Upload-Length"]

4. 验证预检响应头

发送OPTIONS请求后,检查响应头是否包含以下字段:

  • Access-Control-Allow-Origin:与前端域名一致
  • Access-Control-Allow-Headers:包含Authorization及tus相关头
  • Access-Control-Allow-Credentials:值为true
    只有这些头正确返回,浏览器才会在POST请求中携带Authorization头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:35:37