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

如何解决Nuxt 3.0.0稳定版中的CORS跨域问题?

环境信息

  • Node 版本:v19.3.0
  • Nuxt 版本:3.0.0 stable

问题描述

该问题在 Nuxt 3.0.0 rc-6 版本中未出现,升级至 Nuxt 3.0.0 稳定版后,开始出现 CORS 问题:

从源地址'http://localhost:3000'访问'https://dev.example.com/v1/example'时被CORS策略阻止:请求的资源上不存在'Access-Control-Allow-Origin'头。如果不透明响应可满足需求,请将请求模式设置为'no-cors'以禁用CORS获取资源。

我使用 ofetch 调用 API,以下是实际代码:

1. /apis/example/example.ts

import http from '@/apis/http'
import * as T from '@/apis/example/types'

const ExampleApi: T.ExampleApi = {
  loadExampleList() {
    return http.get(`/v1/example`)
  },
  loadExampleData(id: number) {
    return http.get(`/v1/example/${id}`)
  },
}
export default ExampleApi

2. /apis/http.ts

import { ofetch } from 'ofetch'

const http = {
  get(url: string) {
    const config = useRuntimeConfig()
    return new Promise((resolve, reject) => {
      ofetch(url, {
        baseURL: config.public.BASE_URL,
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
          Uuid: uuid,
        },
        onResponse({ response }) {
          if (response.ok) {
            resolve(response._data)
          }
        },
      }).catch(err => {
        reject(err)
      })
    })
  },
}
export default http

3. /nuxt.config.ts

import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  modules: ['@pinia/nuxt'],
  css: ['@/assets/scss/style.scss'],
  hooks: {
    'components:dirs'(dirs: any) {
      dirs.push({
        path: '~/components',
      })
    },
  },
  components: {
    global: true,
  },
  nitro: {
    preset: 'aws-lambda',
    serveStatic: true,
  },
  app: {
    baseURL: '/',
  },
  typescript: {
    shim: false,
    strict: true,
  },
})

我了解到可以将端点文件放置在 server/api/ 目录下,但由于需要处理大量端点,希望避免这种方式。

附言:该问题已在无需服务端修复的情况下得到解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:55:22