You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中Axios请求Host头为127.0.0.1而非localhost的解决方法

如何让Axios在Node.js中设置Host请求头为localhost?

问题描述

我在Node.js服务端应用中使用Axios向另一服务器发送请求,代码如下:

axios({
    method: "GET",
    url: "https://base.url.to.another.server/myapi",
})
.catch(function (error) 
{
    if (error) 
        return reject(error);
})
.then(function (resp) 
{
    resolve(resp);
    return resp;
}); 

请求可正常发送,但接收方服务器收到的Host头值为127.0.0.1而非localhost,触发安全策略异常;通过浏览器发送相同请求时,Host头值为正确的localhost。

已尝试直接在headers中设置'host': 'localhost:8080',但未生效。

解决方案

1. 明确在请求配置中设置Host头

Node.js环境下,Axios依赖的http/https模块会自动根据请求目标的解析结果设置Host头,直接设置小写host可能被底层模块覆盖,需在请求headers中明确指定Host字段:

axios({
    method: "GET",
    url: "https://base.url.to.another.server/myapi",
    headers: {
        'Host': 'localhost:8080' // 强制设置Host头
    }
})
.then(resp => {
    // 处理响应逻辑
})
.catch(error => {
    // 处理错误逻辑
});

2. 创建独立Axios实例隔离全局配置

若全局Axios存在拦截器或默认头覆盖的情况,可创建自定义实例避免干扰:

const customAxios = axios.create({
    headers: {
        'Host': 'localhost:8080'
    }
});

customAxios.get("https://base.url.to.another.server/myapi")
.then(resp => {
    // 处理响应
})
.catch(error => {
    // 处理错误
});

3. HTTPS请求配合httpsAgent设置SNI

如果目标服务器依赖SNI(Server Name Indication)识别主机名,需同时配置httpsAgent的servername参数,确保与Host头一致:

const https = require('https');

const agent = new https.Agent({
    servername: 'localhost' // 匹配Host头的主机名
});

axios({
    method: "GET",
    url: "https://base.url.to.another.server/myapi",
    httpsAgent: agent,
    headers: {
        'Host': 'localhost:8080'
    }
})
.then(resp => {
    // 处理响应
})
.catch(error => {
    // 处理错误
});

关键说明

  • Node.js的http/https模块默认会根据请求目标的IP或解析后的域名自动设置Host头,手动设置的Host头需确保优先级高于默认值。
  • 若请求目标URL为IP地址(而非域名),必须手动设置Host头,否则默认会使用IP作为Host值。

内容的提问来源于stack exchange,提问作者Atul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:36:21