NodeJS请求库如何获取完整的URL,包括URI和查询字符串参数

时间:2018-07-24 11:28:39

标签: node.js node-request

一个人如何从使用NodeJS request库执行的HTTP请求中提取/查找完整URL。这对于日志记录很有用。

这是一个代码示例来演示:

request({
    baseUrl: 'https://foo.bar',
    url: '/foobar',
    qs: {
        page: 1,
        pagesize: 25
    }
}, (err, res, body) => {
    // Somewhere here I'd expect to find the full url from one of the parameters above
    // Expected output: https://foo.bar/foobar?page=1&pagesize=25
    console.log(res);
});

在包含URL的回调中,我似乎找不到res参数的任何属性。

为了阐明这一点:通过完整的URL表示由请求库构建的URL,其中应包括以下字段:

  • 基本URL(或在未设置基本URL的情况下仅为URI / URL)
  • URL(或URI)
  • 查询字符串参数

1 个答案:

答案 0 :(得分:2)

实际上,您可以在创建请求时轻松存储请求。

const request = require('request');
const myReq = request({
    baseUrl: 'https://foo.bar',
    url: '/foobar',
    qs: {
        page: 1,
        pagesize: 25
    }
}, (err, res, body) => {
    console.log(myReq.host); // BASE URL
    console.log(myReq.href); // Request url with params
});
相关问题