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

标签 node.js node-request

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

这里有一个代码示例来演示:

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)
  • 查询字符串参数

最佳答案

实际上,您可以通过在创建请求时存储您的请求来轻松做到这一点。

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
});

关于node.js - NodeJS 请求库如何获取完整的 URL,包括 URI 和查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51497450/

相关文章:

node.js 请求多行

javascript - 等待所有nodeJS请求完成并给它们添加一个小延迟

javascript - 在 MVC 结构中使用 Express + Request Node 模块的异步嵌套回调

javascript - Mongodb 中包含位置信息的文档

android - https ://www. googleapis.com/oauth2/v3/certs 中 v1、v2 和 v3 之间的区别

json - couchdb - 导入 json 文件

javascript - Instagram 实时 OAuthParameterException : missing client_id or access_token URL parameter. 在 _request

javascript - 错误: Cannot find module 'dbconstant'

node.js - browserify watchify 产生错误

javascript - NodeJS 请求模块 - http.IncomingMessage 上的正文?