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

Nuxt3中useFetch遇CORS错误,如何确保请求走Nuxt服务器?

解决方案

方法一:强制useFetch在服务器端发起

useFetch提供了server配置项,设置为true后,无论SSR渲染还是客户端路由跳转(nuxt-link),请求都会通过Nuxt服务器发起,避免客户端直接请求外部接口导致的CORS错误。

修改你的app.vue代码:

<script setup>
const route = useRoute();
const { data, refresh } = await useFetch(`https://thesite.net/${route.path}`, {
  // 强制请求在Nuxt服务器端执行
  server: true
});

watch(() => route.path, async () => {
  await refresh();
});
</script>

当客户端通过nuxt-link跳转时,Nuxt会在服务器端重新执行useFetch请求,再将数据返回给客户端,不会触发浏览器的CORS校验。

方法二:配置Nuxt代理(更推荐)

通过配置反向代理,将前端请求转发到Nuxt服务器,再由服务器代理请求目标接口,彻底解决跨域问题,同时还能隐藏目标接口地址,提升安全性。

  1. 安装代理模块:
npm install @nuxtjs/proxy
  1. 在nuxt.config.ts中配置代理:
export default defineNuxtConfig({
  modules: ['@nuxtjs/proxy'],
  proxy: {
    '/api': {
      target: 'https://thesite.net',
      changeOrigin: true,
      pathRewrite: { '^/api': '' }
    }
  }
});
  1. 修改app.vue中的请求路径为相对路径:
<script setup>
const route = useRoute();
const { data, refresh } = await useFetch(`/api/${route.path}`);

watch(() => route.path, async () => {
  await refresh();
});
</script>

此时所有请求都会先发送到Nuxt服务器的/api路径,再由代理转发到目标接口https://thesite.net,完全规避CORS问题。

问题原因说明

你之前的代码中,useFetch默认在SSR阶段由服务器发起请求(无跨域),但通过nuxt-link跳转时,请求会在客户端浏览器中发起,直接访问外部接口触发了浏览器的CORS同源策略校验,导致错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 20:15:09