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

使用window处理API请求遇window未定义错误,如何优化Base URI?

解决Nuxt中window未定义错误并优化Base URI处理

出现window is not defined是因为Nuxt的SSR(服务端渲染)机制:代码会先在服务端(Nitro)执行,而服务端环境不存在浏览器的window对象,因此抛出错误。以下是几种优化方案:

方案一:使用Nuxt运行时配置(推荐)

Nuxt提供useRuntimeConfig()统一管理环境配置,支持客户端和服务端通用,无需手动判断环境。

  1. 在nuxt.config.ts中配置环境变量:
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiBase: process.env.NODE_ENV === 'development' 
        ? 'http://localhost:3000' 
        : 'https://something.com'
    }
  }
})
  1. 在组件中调用配置:
const getProducts = async () => {
  isLoading.value = true;
  const config = useRuntimeConfig();
  
  return await useFetch(`${config.public.apiBase}/assets/json/data.json`, {
    onRequestError({ request, options, error }) {
      console.log(error);
      isLoading.value = false;
    },
    onResponse({ request, response, options }) {
      let pricing = new Map(response._data['Regency Pricing'].map(o => [o['Part Num'], o]))
      products.value = response._data['Product Info'].map(o => ({ ...pricing.get(o['Pricing Reference Name']), ...o }))
      setFilters();
      isLoading.value = false;
    },
    onResponseError({ request, response, options }) {
      console.log(request.error);
      isLoading.value = false;
    }
  });
};

方案二:直接使用相对路径

如果data.json放在项目的public/assets/json/目录下,直接用相对路径即可。Nuxt会自动根据当前环境补全Base URI,无需手动拼接:

const getProducts = async () => {
  isLoading.value = true;
  
  return await useFetch('/assets/json/data.json', {
    onRequestError({ request, options, error }) {
      console.log(error);
      isLoading.value = false;
    },
    onResponse({ request, response, options }) {
      let pricing = new Map(response._data['Regency Pricing'].map(o => [o['Part Num'], o]))
      products.value = response._data['Product Info'].map(o => ({ ...pricing.get(o['Pricing Reference Name']), ...o }))
      setFilters();
      isLoading.value = false;
    },
    onResponseError({ request, response, options }) {
      console.log(request.error);
      isLoading.value = false;
    }
  });
};

方案三:仅在客户端使用window(不推荐)

如果必须依赖window,可以通过Nuxt提供的process.client变量判断,仅在客户端执行相关逻辑:

const getProducts = async () => {
  isLoading.value = true;
  const baseUrl = process.client ? window.location.origin : '';
  
  return await useFetch(`${baseUrl}/assets/json/data.json`, {
    onRequestError({ request, options, error }) {
      console.log(error);
      isLoading.value = false;
    },
    onResponse({ request, response, options }) {
      let pricing = new Map(response._data['Regency Pricing'].map(o => [o['Part Num'], o]))
      products.value = response._data['Product Info'].map(o => ({ ...pricing.get(o['Pricing Reference Name']), ...o }))
      setFilters();
      isLoading.value = false;
    },
    onResponseError({ request, response, options }) {
      console.log(request.error);
      isLoading.value = false;
    }
  });
};

注意:这种方式下服务端请求会因baseUrl为空失败,仅适用于资源只在客户端加载的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:13:13