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

Nginx反向代理下Axios请求指向IP:Port而非域名问题排查

问题排查与解决方案

1. 确认window.config.baseURL的实际值

先检查浏览器控制台的日志输出,确认Initial baseURL和Setting new baseURL打印的内容是不是预期的https://sub.domain.tld。如果值不对,大概率是config.js的加载时机有问题:

  • 确保config.js在main.js之前加载(比如在index.html里把<script src="config.js">放在最前面);
  • 在main.js开头添加console.log('window.config:', window.config),直接查看全局变量的实际内容。

2. 修复Axios客户端的实例更新逻辑

当前用computed创建Axios实例,虽每次访问client都会生成新实例,但组件中可能存在引用缓存的情况。建议改用watch监听baseURL变化来更新客户端:

export const useApiStore = defineStore('api', () => {
  const baseURL = ref(window.config.baseURL || '');
  // 初始化Axios客户端
  const client = ref(axios.create({ baseURL: baseURL.value }));

  const setBaseURL = (url) => {
    baseURL.value = url;
  };

  // 监听baseURL变化,更新客户端实例
  watch(baseURL, (newUrl) => {
    client.value = axios.create({ baseURL: newUrl });
    console.log('Axios client updated with baseURL:', newUrl);
  });

  return { baseURL, client, setBaseURL };
});

组件中调用时,确保访问最新的client.value:

const apiStore = useApiStore();
const response = await apiStore.client.value.post('/api/v1/start', payload);

3. 排查FastAPI与反向代理配置

FastAPI端配置

确保FastAPI正确识别反向代理传递的头部,避免协议/域名错误:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

# 信任反向代理传递的主机头,正确识别外部协议与域名
app = FastAPI(trust_host=True)
# 挂载前端静态文件
app.mount("/", StaticFiles(directory="dist", html=True), name="static")

# 配置CORS,允许目标域名访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://sub.domain.tld"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Nginx Proxy Manager配置

即使是默认配置,也要确保开启Forward Host Header选项,或者添加自定义Nginx配置:

proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;

这些头部会让FastAPI知晓请求的实际协议(HTTPS)和域名。

4. 清除浏览器缓存

浏览器可能缓存了旧的静态资源(比如config.js),导致配置未更新。直接按Ctrl+F5强制刷新页面,或者清除浏览器缓存后重新测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:42:35