Node.js中如何发送含重复Authorization头的HTTP请求?
方法1:使用Node.js原生http/https模块
原生模块支持直接以数组形式定义请求头,完美适配重复键的需求,无需额外依赖:
const https = require('https'); const postData = JSON.stringify({ foo: "bar" }); const options = { hostname: 'service.com', path: '/test', method: 'POST', headers: [ ['Authorization', 'Basic token'], ['Authorization', 'Bearer token'], ['Content-Type', 'application/json'], ['Content-Length', Buffer.byteLength(postData)] ] }; const req = https.request(options, (res) => { res.on('data', (d) => { process.stdout.write(d); }); }); req.on('error', (e) => { console.error(e); }); req.write(postData); req.end();
这里将headers设为二维数组,每个子数组对应一组[键名, 值],发送逻辑和你成功的curl命令完全一致。
方法2:使用支持重复请求头的HTTP库
不少主流库提供了绕过字典限制的方式,以下是几个可行选项:
Got库
明确支持数组形式定义请求头:
const got = require('got'); (async () => { try { const response = await got.post('https://service.com/test', { headers: [ ['Authorization', 'Basic token'], ['Authorization', 'Bearer token'], ['Content-Type', 'application/json'] ], json: { foo: "bar" } }); console.log(response.body); } catch (error) { console.error(error); } })();
Superagent库
通过多次调用.set()方法添加重复头:
const superagent = require('superagent'); superagent.post('https://service.com/test') .set('Authorization', 'Basic token') .set('Authorization', 'Bearer token') .set('Content-Type', 'application/json') .send({ foo: "bar" }) .then(res => console.log(res.body)) .catch(err => console.error(err));
Axios的适配方案
Axios默认用对象存储头,但部分版本支持数组形式的头值:
const axios = require('axios'); axios.post('https://service.com/test', { foo: "bar" }, { headers: { 'Authorization': ['Basic token', 'Bearer token'], 'Content-Type': 'application/json' } }).then(res => console.log(res.data)) .catch(err => console.error(err));
如果上述方式不生效,直接使用原生http/https模块会更稳妥。
补充说明
HTTP标准中仅部分头字段支持逗号分隔值,但Authorization不属于此类字段,第三方API明确要求两个独立的请求头,因此拼接值的方式不符合对方的解析逻辑,无法生效。
内容的提问来源于stack exchange,提问作者Jetser94
相关产品推荐
相关产品推荐

