如何从使用 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/