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

使用react-doc-viewer展示源文件时出现401错误:Cookie未发送至API

问题解决:react-doc-viewer 请求API返回401(Cookie未携带)

问题描述

在React应用中使用@cyntler/react-doc-viewer组件展示DOCX、文本等文件时,调用API接口返回401未授权错误。排查发现请求未携带API认证所需的Cookie,而API依赖Cookie完成身份校验。

当前代码:

import DocViewer, { DocViewerRenderers } from "@cyntler/react-doc-viewer";

export const FileViewer = (props) => {
    const { path } = props;
    const headers = { withCredentials: true };
    const docs = [{ uri: path }];
    console.log(path);
    return (
        <DocViewer
            documents={docs}
            pluginRenderers={DocViewerRenderers}
            prefetchMethod="GET"
            requestHeaders={headers}
        />
    );
};

问题原因

withCredentials并不是HTTP请求头的一部分,它是XMLHttpRequest/fetch API的专属配置选项,不能放在requestHeaders对象中传递。当前代码的写法导致组件无法正确识别这个配置,最终请求没有携带Cookie。

解决方案

方法1:使用组件的requestOptions属性(推荐)

@cyntler/react-doc-viewer支持通过requestOptions传递请求级别的配置项,将withCredentials: true放在这个配置对象里即可:

import DocViewer, { DocViewerRenderers } from "@cyntler/react-doc-viewer";

export const FileViewer = (props) => {
    const { path } = props;
    const docs = [{ uri: path }];
    console.log(path);
    return (
        <DocViewer
            documents={docs}
            pluginRenderers={DocViewerRenderers}
            prefetchMethod="GET"
            requestOptions={{ withCredentials: true }}
        />
    );
};

方法2:检查后端API的CORS配置

如果修改组件配置后仍然报错,需要确认后端API的跨域设置是否正确:

  • 必须在响应头中添加Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Origin不能设为通配符*,必须指定前端应用的具体域名(例如http://localhost:3000)

验证方式

修改完成后,打开浏览器开发者工具(F12),切换到网络面板:

  1. 查看对应API请求的Cookie标签,确认认证Cookie已被携带
  2. 检查请求的响应状态码是否变为200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:02:05