【问题标题】:Cors error persists if the page is not refreshed in Nuxt如果页面未在 Nuxt 中刷新,Cors 错误仍然存​​在
【发布时间】:2021-12-29 17:38:49
【问题描述】:

我刚开始学习 Nuxt。 当我尝试通过 <nuxt-link> 访问页面时遇到 CORS 问题。
如果我刷新页面或者我通过<a href="">进行操作,问题就解决了

<template>
  <div>
    <p>{{ author }}</p>
    <button @click="$fetch">Fetch</button>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  useFetch,
  useContext,
  ref
} from '@nuxtjs/composition-api'
export default defineComponent({
  name: 'ArticleAuthor',
  setup() {
    const author: any = ref(null)
    const { $http, $config } = useContext()
    const apiSecret = Buffer.from($config.apiSecret).toString('base64')
    const { fetch } = useFetch(async () => {
      author.value = await $http.$get(
        `https://zendeskhelpsandbox.zendesk.com/api/v2/users/1904135029254`,
        {
          headers: {
            Authorization: `Basic ${apiSecret}`
          }
        }
      )
    })
    return { author, fetch }
  }
})
</script>

【问题讨论】:

  • 错误消息(在浏览器的控制台选项卡中)是什么意思?
  • 访问从源 'localhost:3000' 获取 'zendeskhelpsandbox.zendesk.com/api/v2/users/1904135029254' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
  • .toString('base64') 在这里做什么?尝试直接使用硬编码,只是为了确定。另外,请不要使用a,这里只有nuxt-link 对SPA/Nuxt 应用程序有效。该错误主要来自这样一个事实,即您正在使用nuxt-link 进行客户端导航,而初始请求是在服务器上完成的(您将没有任何 CORS)。此外,检查您的网络选项卡(您发送、接收的内容),并确保您的后端已将 Nuxt 的应用 IP 列入白名单。
  • 有问题的端点似乎不支持 CORS。在对预检请求的响应中,我看不到任何 CORS 标头。
  • 你有反向代理吗?似乎应用程序在 localhost:3000 上运行,我会在 fetch /api/v2/users/1904135029254 中尝试这个,只是丢失域

标签: cors nuxt.js vue-composition-api zendesk-api


【解决方案1】:

解决方案: 我使用了代理并添加了一个'Access-Control-Allow-Origin': '*'

<script lang="ts">
import {
  defineComponent,
  useFetch,
  useContext,
  ref
} from '@nuxtjs/composition-api'
export default defineComponent({
  name: 'ArticleAuthor',
  setup() {
    const author: any = ref(null)
    const { $http, $config } = useContext()
    const apiSecret = Buffer.from($config.apiSecret).toString('base64')
    const { fetch } = useFetch(async () => {
      author.value = await $http.$get(
          `/api/users/1904135029254`,
          {
            headers: {
              Authorization: `Basic ${apiSecret}`,
              'Access-Control-Allow-Origin': '*'
            }
          }
        )
    })
    return { author, fetch }
  }
})
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2013-09-12
    • 2017-08-18
    • 2022-01-20
    • 2020-04-17
    • 2020-12-30
    • 2011-12-10
    相关资源
    最近更新 更多