6

有没有办法在初始化后更改 nano 中的配置参数?我想用以下方法初始化 nano:

nano = require('nano')('http://127.0.0.1:5984')

然后在用户提交登录表单后更改用户和密码。我总是得到一个错误:

nano.cfg.user = params.user.name
TypeError: Cannot set property 'user' of undefined

还是我应该分叉 nano 并编写一个身份验证函数来调整值?

4

2 回答 2

5

我现在无法对其进行测试,但是,查看源代码,您可以注意到两件事:

然后我认为您需要使用身份验证参数将 url 配置选项设置为新值:

nano.config.url = 'http://' + params.user.name + ':' + params.user.password + '@localhost:5984';

或者您可以像在couch.example.js中一样保留配置对象并执行以下操作:

cfg.user = params.user.name;
cfg.pass = params.user.password;
nano.config.url = cfg.url;

更新:这是一个完整的例子:

var cfg = {
  host: "localhost",
  port: "5984",
  ssl: false
};

cfg.credentials = function credentials() {
  if (cfg.user && cfg.pass) {
    return cfg.user + ":" + cfg.pass + "@";
  }
  else { return ""; }
};

cfg.url = function () {
  return "http" + (cfg.ssl ? "s" : "") + "://" + cfg.credentials() + cfg.host +
    ":" + cfg.port;
};

var nano = require('nano')(cfg.url()),
  db = nano.use('DB_WITH_AUTH'),
  docId = 'DOCUMENT_ID';

function setUserPass(user, pass) {
  cfg.user = user;
  cfg.pass = pass;
  nano.config.url = cfg.url();
}

db.get(docId, function (e, r, h) {
  if (e) {
    if (e['status-code'] === 401) {
      console.log("Trying again with authentication...");
      setUserPass('USENAME', 'PASSWORD');
      db.get(docId, function (e, r, h) {
        if (e) {
          console.log("Sorry, it did not work:");
          return console.error(e);
        }
        console.log("It worked:");
        console.log(r);
        console.log(h);
      });
      return;
    }
    console.log("Hmmm, something went wrong:");
    return console.error(e);
  }
  console.log("No auth required:");
  console.log(r);
  console.log(h);
});
于 2011-10-06T09:32:56.587 回答
2

身份验证可以作为 http 标头的一部分发送:

if(cfg.user && cfg.pass) {
  req.headers['Authorization'] = "Basic " + new Buffer(cfg.user+":"+cfg.pass).toString('base64');
}

用户名和密码可以使用 'auth'-function 设置:

function auth_db(user, password, callback) {
  cfg.user = user;
  cfg.pass = password;
  return relax({db: "_session", method: "GET"}, callback);
}
于 2011-10-06T12:09:40.520 回答