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

Nuxt3中调用refresh()触发Chrome浏览器CORS错误求助

解决Nuxt3 + nuxt-graphql-client客户端刷新时的CORS问题

问题根源

SSR阶段的请求由Nuxt服务器发起,不受浏览器CORS策略限制;而用户交互触发的refresh()是浏览器直接向Apollo Server(http://localhost:3001)发送请求,跨域触发了浏览器的CORS校验,因此报错。

解决方案

1. 配置Apollo Server允许跨域请求

在Apollo Server的启动代码中,明确配置CORS规则,允许Nuxt的域名(http://localhost:3000):

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

const server = new ApolloServer({ typeDefs, resolvers });

const { url } = await startStandaloneServer(server, {
  listen: { port: 3001 },
  // 配置CORS规则
  cors: {
    origin: 'http://localhost:3000', // 指定允许的来源域名
    credentials: true, // 若请求需要携带Cookie等凭证则开启
  },
});

如果需要适配多环境,可将origin设为数组或动态判断的函数。

2. 用Nuxt代理转发请求(开发环境推荐)

若不想修改后端配置,可在Nuxt中配置代理,让客户端请求先发到同域的Nuxt服务器,再由Nuxt转发到Apollo Server:

  • 先安装代理依赖:
npm install @nuxtjs/proxy
  • 在nuxt.config.ts中添加配置:
export default defineNuxtConfig({
  modules: ['nuxt-graphql-client', '@nuxtjs/proxy'],
  // 代理规则配置
  proxy: {
    '/graphql': {
      target: 'http://localhost:3001',
      changeOrigin: true,
    },
  },
  // 修改graphql-client的请求地址为相对路径
  'graphql-client': {
    clients: {
      default: {
        host: '/graphql',
      },
    },
  },
});

通过代理转发后,客户端请求不再跨域,自然规避CORS错误。

3. 修正useAsyncGql的参数传递问题

你的代码中,useAsyncGql直接传入searchQuery.value会导致初始值固定,refresh()时无法读取最新的搜索值。可通过两种方式修正:

方式一:直接传递响应式变量

const { data, refresh } = await useAsyncGql('MyGqlQuery', { 
  name: { contains: searchQuery } // 传入ref本身,而非.value
})

方式二:refresh时手动传入最新参数

const onKeyboardInput = async (newSearchQuery) => {
  searchQuery.value = newSearchQuery
  await refresh({ name: { contains: newSearchQuery } }) // 手动传递最新搜索值
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 10:33:25