我有一个URL对象,我需要使用 http
模块在 node.js 中发出请求。
通常我使用:
const url = new URL('...'); // from third party module
http.request(url)
但我需要向请求添加 header 。
const url = new URL('...'); // from third party module
http.request({
hostname: url.hostname,
port: url.port,
path: url.path,
method: 'post'
headers: {...}
});
我猜测是否有一种方法可以将 URL 对象转换为选项对象,以避免使用旧版 url.parse(文档本身不推荐)。
Note: While the Legacy API has not been deprecated, it is maintained solely for backwards compatibility with existing applications. New application code should use the WHATWG API.
实际上,如何手动执行 http.request
参数文档中所述的操作:
If it is a URL object, it will be automatically converted to an ordinary options object.
如果我将 Object.assign
与 URL 对象一起使用,它会公开创建的最终对象的一些内部信息,我找到的唯一解决方案是手动提取所需的属性...
这是一个设计缺陷还是我错过了什么?
最佳答案
从 Node v10.9.0 开始,可以分别传递 url(字符串或 URL 实例)和选项参数。这是新的函数签名:
http.request(url[, options][, callback])
对于旧版本,没有直接的方法来合并 URL 对象和选项。在幕后,Node.js converts URL object to options object使用与您类似的方法。
关于node.js - 使用 URL 对象发送 HTTP 请求但添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179477/