CouchDb 2.1.1 管理员 API 压实 PUT 请求

CouchDb 2.1.1 Admin API Compaction PUT Request

我在 NodeJS 和 CouchDB 2.1.1 中工作。

我正在使用 http.request() 方法通过 CouchDB API.

设置各种配置设置

这是他们的 API 参考资料,是的,我读过它:

Configuration API

这是设置日志记录级别的工作请求示例:

const http = require('http');

var configOptions = {
    host: 'localhost',
    path: '/_node/couchdb@localhost/_config/',
    port:5984,
    header: {
        'Content-Type': 'application/json'
    }
};

function setLogLevel(){
    configOptions.path = configOptions.path+'log/level';
    configOptions.method = 'PUT';
    var responseString = '';
    var req = http.request(configOptions, function(res){
        res.on("data", function (data) {
            responseString += data;
        });
        res.on("end", function () {
            console.log("oldLogLevel: " + responseString);
        });
    });

    var data = '\"critical\"';

    req.write(data);
    req.end();
}

setLogLevel();

我不得不转义所有引号等,这是预料之中的。

现在我正在尝试让 CouchDb 接受压缩设置。

问题是我试图将相同的请求复制到不同的设置,但该设置没有简单的结构,尽管它看起来也是 "just a String"。

CouchDB API 对我大喊 JSON 格式无效,我尝试了一大堆转义序列并尝试以各种方式解析 JSON 以获取它以我认为应该的方式行事。

我可以使用Chrome的Advanced Rest Client发送这个payload,而且成功了:

Request Method: PUT
Request URL: http://localhost:5984/_node/couchdb@localhost/_config/compactions/_default
Request Body:  "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]"

这 returns 一个“200 OK”

当我在我的节点应用程序中执行以下功能时,我得到的响应是:

{"error":"bad_request","reason":"invalid UTF-8 JSON"}

function setCompaction(){
    configOptions.path = configOptions.path+'compactions/_default';
    configOptions.method = 'PUT';
    var responseString = '';
    var req = http.request(configOptions, function(res){
        res.on("data", function (data) {
            responseString += data;
        });
        res.on("end", function () {
            console.log("oldCompaction: " + responseString); 
        });
    });

    var data = "\"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]\"";

    req.write(data);
    req.end();
}

有人可以指出我在这里遗漏了什么吗?

提前致谢。

您需要使用节点的 JSON 模块来准备传输数据:

var data = '[{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}]';

// Show the formatted data for the requests' payload.
JSON.stringify(data);

> '"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:
00\"}, {to, \"04:00\"}]"'

// Format data for the payload.
req.write(JSON.stringify(data));