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

PouchDB创建远程数据库添加自定义Header时出现报错该如何解决?

PouchDB 自定义请求头报错解决方案

错误1:export 'fetch' (imported as 'PouchDB') was not found in 'pouchdb'

该报错由ES模块导入规则与PouchDB导出逻辑不匹配导致,可通过两种方案修复:

  • 调整导入语法为默认导入:
    // 错误导入写法
    // import * as PouchDB from 'pouchdb'
    // 正确导入写法
    import PouchDB from 'pouchdb'
    
  • 若调整导入后仍报错,可直接替换为原生fetch方法,功能完全一致:
    return fetch(url, opts)
    

额外注意当前代码的this指向问题:你使用普通函数声明fetch配置项,函数内部的this会指向PouchDB实例而非外层上下文,会导致this.text取值异常,可改为箭头函数绑定外层this。

错误2:set does not exist on type headersinit

该报错是因为opts.headers可能是普通JS对象而非Headers类实例,普通对象没有set方法,可通过两种方案修复:

  • 先转换为Headers实例再操作:
    opts.headers = new Headers(opts.headers || {});
    opts.headers.set('xx-custom-xx', this.text);
    
  • 直接用对象属性赋值的方式添加请求头,无需调用set方法:
    opts.headers = opts.headers || {};
    opts.headers['xx-custom-xx'] = this.text;
    

完整可运行代码示例

import PouchDB from 'pouchdb';

const db = new PouchDB(this.server, {
  fetch: (url, opts) => {
    opts.headers = opts.headers || {};
    opts.headers['xx-custom-xx'] = this.text;
    opts.credentials = 'include';
    return fetch(url, opts);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:06:03