简体   繁体   中英

How to resolve CORS issue in Nuxt3.0.0?

  • Node Version: v19.3.0

  • Nuxt Version: 3.0.0 stable

Describe the bug

It's a problem that didn't reproduce on Nuxt 3.0.0 rc-6.

After upgrading to Nuxt 3.0.0 stable, I started having CORS issues.

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.

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,
  },
})

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...

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).

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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

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.

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.

If you are the owner of that domain, just try changing CORS headers for a while, or set a more flexible CORS policy.

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. This is not recommended for production environments but it might be useful for development and testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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