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

为何localhost:8000/api作为Axios baseURL时出现网络错误?

本地Axios请求ERR_NETWORK错误修复指南

问题场景

搭建Axios配置用于获取用户信息,使用本地baseURL "https://localhost:8000/api" 时出现ERR_NETWORK错误,替换为线上baseURL后功能正常。配置代码及错误信息如下:

Axios配置代码

import axios from "axios";
import dayjs from "dayjs";
import { toast } from "react-toastify";

export const api = axios.create({
  baseURL: "https://localhost:8000/api",
});

export const getAllProperties = async () => {
  try {
    const response = await api.get("./residency/allresd", {
      timeout: 10 * 1000,
    });

    if (response.status === 400 || response.status === 500) {
      throw response.data;
    }
    return response.data;
  } catch (error) {
    toast.error("Something went wrong");
    throw error;
  }
};

错误信息

AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code: "ERR_NETWORK"
config: {
  baseURL: "https://localhost:8000/api",
  url: "./residency/allresd",
  method: "get",
  ...
}
message: "Network Error"

修复步骤

1. 修正请求路径格式

请求路径开头的./会导致Axios URL拼接逻辑异常,去掉前缀改为绝对路径写法:

export const getAllProperties = async () => {
  try {
    // 改为以/开头的路径
    const response = await api.get("/residency/allresd", {
      timeout: 10 * 1000,
    });

    if (response.status === 400 || response.status === 500) {
      throw response.data;
    }
    return response.data;
  } catch (error) {
    toast.error("Something went wrong");
    throw error;
  }
};

修改后Axios会自动拼接成正确地址:https://localhost:8000/api/residency/allresd。

2. 检查本地后端服务状态

  • 确认https://localhost:8000服务已启动,直接在浏览器访问https://localhost:8000/api/residency/allresd,验证是否能正常返回数据
  • 检查后端是否配置了CORS跨域支持:前端运行在localhost:3000,请求localhost:8000属于跨域场景,后端需允许该来源的请求
  • 核对后端接口路径是否正确:确认/api/residency/allresd是实际存在的接口,避免拼写错误(比如代码中的allresd是否应为allresidency)

3. 验证baseURL格式

当前baseURL "https://localhost:8000/api" 格式正确,无需修改。注意不要在baseURL结尾添加多余的/,否则会和路径开头的/拼接出重复斜杠。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:57:48