CouchDB 无法使用pouchdb保存ddoc/索引

jckbn6z7  于 2022-12-09  发布在  CouchDB
关注(0)|答案(1)|浏览(218)

我尝试在我的数据上建立索引,但是我总是收到这个错误。我已经暂时移除数据库的所有权限,让它运作,但是仍然没有成功。

{
  error: 'error_saving_ddoc',
  reason: 'Unknown error while saving the design document: unauthorized',
  ref: 612684199,
  status: 500,
  name: 'error_saving_ddoc',
  message: 'Unknown error while saving the design document: unauthorized'
}

我的代码:

(async () => {
    let db:any = new PouchDB('http://localhost:5984/test', { skip_setup: true });
    await db.createIndex({
      index: {fields: ['area']}
    })
    let res = await db.find({
        selector: {'area': {$gt: null}},
        fields: ['_id', 'area'],
        sort: ['_id']
      });
})();

我也尝试过安装pouchdb-authentication,并使用下面的代码成功登录,但我仍然无法使用上面的代码创建索引。
验证码:

this.db.logIn('admin', 'password').then((x)=>{
  console.log("This works");
}).catch(e=>console.log(e));

我该怎么做才能让它工作呢?

iyzzxitl

iyzzxitl1#

我认为pouchdb身份验证是一个复杂的问题[1],并且存在关于该插件的已知问题[2,3]。
我的 * 意见 * 是使用HTTPS的基本身份验证是最好的大多数用例。我看到pouchdb-authentication是方便的情况下,有需要经常切换凭据来执行各种任务。
下面的代码演示了不同的认证方式。这段代码可以在nodejs上运行,但是如果服务器端的CORS设置正确,那么它也可以很容易地适应浏览器[4]。

let PouchDB = require("pouchdb");
PouchDB.plugin(require("pouchdb-find"));
PouchDB.plugin(require("pouchdb-authentication"));

const testUrlTemplate = "http://*127.0.0.1:5984/test";

const doTask = async (db) => {
  await db.createIndex({
    index: { fields: ["area"] },
  });

  return await db.find({
    selector: { area: { $gt: null } },
    fields: ["_id", "area"],
    sort: ["area"],
  });
};

// connect to remote db using basic auth (preferred with https)
const basicAuth = async (credentials) => {
  const url = testUrlTemplate.replace("*", "");
  return new PouchDB(url, {
    skip_setup: true,
    auth: credentials,
  });
};
// connect to remote db using unwise cleartext 
const unwiseUrl = async (credentials) => {
  const url = testUrlTemplate.replace(
    "*",
    `${credentials.username}:${credentials.password}@`
  );
  return new PouchDB(url, {
    skip_setup: true,
  });
};

// convenience.
const log = (obj) => {
  console.log(JSON.stringify(obj));
};

(async () => {
  try {
    const credentials = {
      username: "some_user",
      password: "some_password",
    };

    let db = await basicAuth(credentials);
    let result = await doTask(db);
    log(result);

    db = await unwiseUrl(credentials);
    result = await doTask(db);
    log(result);

    // use basic auth the init the db, then switch to another user
    // with a cookie session.
    db = await basicAuth(credentials);
    await db.logIn("plain_user", "plaintext_password");
    result = await doTask(db);
    log(result);
  } catch (err) {
    // oopsy
    log(result);
  }
})();

请注意,我修改了查找代码,因为sort参数会破坏查询。
1 PouchDB安全性
2个
3个pouchdb-authentication issue #204
4个Add CORS to CouchDB

相关问题