简体   繁体   English

Nuxt3.0.0 CORS 问题如何解决?

[英]How to resolve CORS issue in Nuxt3.0.0?

  • Node Version: v19.3.0节点版本: v19.3.0

  • Nuxt Version: 3.0.0 stable Nuxt 版本: 3.0.0 stable

Describe the bug描述错误

It's a problem that didn't reproduce on Nuxt 3.0.0 rc-6.这是一个在 Nuxt 3.0.0 rc-6 上没有重现的问题。

After upgrading to Nuxt 3.0.0 stable, I started having CORS issues.升级到 Nuxt 3.0.0 稳定版后,我开始遇到 CORS 问题。

Access to fetch at 'https://dev.example.com/v1/example' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I'm calling an API with ofetch and this is the actual code.我正在使用 ofetch 调用 API,这是实际代码。

1. 1. /apis/example/example.ts /apis/例子/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. 2. /apis/http.ts /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. 3. /nuxt.config.ts /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,
  },
})

There seems to be a way to put the endpoints files in server/api/ but I'm dealing with a lot of endpoints so I'd like to avoid this...似乎有一种方法可以将端点文件放在 server/api/ 中,但我正在处理很多端点,所以我想避免这种情况......

https://github.com/nuxt/framework/blob/v3.0.0-rc.4/docs/content/2.guide/2.features/9.server-routes.md#example https://github.com/nuxt/framework/blob/v3.0.0-rc.4/docs/content/2.guide/2.features/9.server-routes.md#example

Your problem is not inside vue (at least not the CORS-related problem).您的问题不在 vue 内部(至少不是与 CORS 相关的问题)。

This message:这条信息:

Access to fetch at 'https://dev.example.com/v1/example' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 政策阻止了从来源“http://localhost:3000”访问“https://dev.example.com/v1/example”:不存在“Access-Control-Allow-Origin”header在请求的资源上。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

It means your localhost is attempting to make a fetch request to "https://dev.example.com/v1/example" but the server at "https://dev.example.com" is not configured to allow this kind of requests.这意味着您的本地主机正在尝试向“https://dev.example.com/v1/example”发出获取请求,但“https://dev.example.com”的服务器未配置为允许这种要求。

This is because of the CORS. The error message specifically mentions that the server at "https://dev.example.com" is not returning a valid header (the "Access-Control-Allow-Origin" header) in its response, which is a necessary step for the browser to determine if your request is allowed or not.这是因为 CORS。该错误消息特别提到位于“https://dev.example.com”的服务器未在其响应中返回有效的 header(“Access-Control-Allow-Origin”标头),这是浏览器确定是否允许您的请求的必要步骤。

If you are the owner of that domain, just try changing CORS headers for a while, or set a more flexible CORS policy.如果您是该域的所有者,请尝试暂时更改 CORS 标头,或设置更灵活的 CORS 策略。

ONLY FOR DEBUGGING:仅用于调试:

Another way to allow this on DEBUGGING is to use a browser extension like Moesif Origin & CORS Changer which allows you to disable CORS security for specific domains on a browser level.在 DEBUGGING上允许这样做的另一种方法是使用浏览器扩展程序,例如 Moesif Origin & CORS Changer,它允许您在浏览器级别上禁用特定域的 CORS 安全性。 This is not recommended for production environments but it might be useful for development and testing.不建议将其用于生产环境,但它可能对开发和测试有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM