如何使用“https”包发送带有 urlencoded 正文的 POST 调用?我无法使用除 https 之外的任何包
“数据”需要进行 URL 编码,因为目标端点需要它 ....
常量选项= { 代理人, 主机名:“myTestURL.com”, 端口:443, 路径:'/foo', 方法:'POST', 标题:{ '内容类型': 'application/x-www-form-urlencoded', }, }
let response = ''
const req = https.request(options, (res) => {
res.on('data', (d) => {
response += d
})
})
req.on('error', (e) => {
console.error(e)
})
req.write(new URLSearchParams(data))
req.end()
只需将数据格式化为 URL 编码并将其包含在请求正文中
这意味着像这样的物体 { key1: '值1', key2: '值2' } 应转换为 'key1=value1&key2=value2'
然后像这样设置请求对象
{ 主机名:'example.com', 路径:'/路径/到/资源', 方法:'POST', 标题:{ '内容类型': 'application/x-www-form-urlencoded', '内容长度': Buffer.byteLength(postData) }
应该可以了!