使用 Node.js 发送 POST 请求

Send a POST request using Node.js

我认为使用 NPM 中的一个模块应该相当容易,但我尝试了两个不同的模块,它们都发送了 URL,但我尽可能不附加标签告诉.

url是:https://safebooru.org/index.php?page=dapi&s=post&q=index 需要发送的是pid,limit,tags。

然而,我一直收到的结果就像我只发送了“https://safebooru.org/index.php?page=dapi&s=post&q=index

而不是说

'https://safebooru.org/index.php?page=dapi&s=post&q=index&pid=1&limit=10&tags=brown_hair'

请。是否有一个模块可以按预期发送这个该死的请求,而不仅仅是提供的基础 URL?

我试过的模块是 'request' 和 'superagent',我是通过 Whosebug 上的类似问题找到的。

const rp = require("request")
const sa = require("superagent");

class SafebooruGetter {
    constructor(data){
        //none
    }

    get(limit, page, tags, callback){
        var results;
        sa.post('https://safebooru.org/index.php?page=dapi&s=post&q=index')
        .send({limit: limit, pid: page, tags: tags})
        .end(function(err, res){
            if(err)
                console.log(err);
            else
                callback(res);
        });

    }


    get2(limit, page, tags){
        var options = {
            method: 'POST',
            url: 'https://safebooru.org/index.php?page=dapi&s=post&q=index',
            form: {
                "limit": limit,
                "pid": page,
                "tags": tags,
            },
            headers: {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
            //json: true
        };
        //console.log(rp(options));
        // return rp(options).then((data) => { return (data)});
        return rp(options, function(error, response, body){
            if(!error && response.statusCode == 200){
                console.log(body);
                return body;
            }
        });
    }
}

您在此将参数作为表单数据发送,

form: {
            "limit": limit,
            "pid": page,
            "tags": tags,
        },

但是您希望它作为这样的查询参数出现 url,

 https://safebooru.org/index.php?page=dapi&s=post&q=index&pid=1&limit=10&tags=brown_hair

那不可能。

如果你想让它只作为查询参数发送,那么就这样发送,

get2(limit, page, tags){
    var options = {
        method: 'POST',
        url: 'https://safebooru.org/index.php?page=dapi&s=post&q=index&pid='+page+'&limit='+limit+'&tags='+tags,
        headers: {
            'User-Agent': 'Super Agent/0.0.1',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        //json: true
    };
    //console.log(rp(options));
    // return rp(options).then((data) => { return (data)});
    return rp(options, function(error, response, body){
        if(!error && response.statusCode == 200){
            console.log(body);
            return body;
        }
    });
}

另一方面,仅像在节点中一样将其作为查询参数捕获,

  var limit = req.query.limit
  var pid = req.query.pid
  var tags = req.query.tags

希望这对您有所帮助。