【问题标题】:CORS axios Nuxt.jsCORS axios Nuxt.js
【发布时间】:2020-01-08 10:45:48
【问题描述】:

我在 Nuxt 中使用 API,这是我的 nuxt.config.js 以允许请求:

axios: {
    prefix: '/api/',
    proxy: true,
  },
  proxy: {
    '/api/': {
      target: process.env.API_URL || 'http://localhost:1337',
      pathRewrite: {
        '^/api/': '/',
      }
    },
  }

在我的应用程序的特定页面上,我需要从另一个域向另一个 API 发送请求。我在这个 Vue 组件中使用 axios 直接:

axios.post('mysite.com/widget.rest')

作为响应,我收到 CORS 错误。我可以在我的配置中允许多个 API 吗?

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    如果您的意思是能够访问不同 URL 下的 API,AFAIK 不可能开箱即用。我们尝试将代理添加到不同的目标,但它只在客户端有效,在 SSR 期间无效。

    我们最终做的是为我们的主 API 使用默认 axios 实例,并创建一个插件,为我们的其他 API 创建额外的 axios 实例用于 SSR。

    1. 向代理添加额外的“suburl” - 这可以解决客户端问题,意味着没有 CORS 问题。
        proxy: {
            '/forum/': {
                target: 'https://other.domain.com/',
                pathRewrite: {'^/forum/': '/'}
            },
            '/api/': ...
        },
    
    1. 要使 SSR 工作,axios 应该直接访问其他 API
    import Vue from 'vue'
    
    var axios = require('axios');
    const forumAxios = axios.create(process.client ? {
        baseURL: "/"
    } : {
        baseURL: 'https://other.domain.com/'
    });
    // this helps Webstorm with autocompletion, otherwise should not be needed
    Vue.prototype.$forumAxios = forumAxios;
    
    export default function (context, inject) {
        if (process.server) {
            forumAxios.interceptors.request.use(function (config) {
                config.url = config.url.replace("/forum/", "");
                return config;
            }, function (error) {
                return Promise.reject(error);
            });
        }
        inject('forumAxios', forumAxios);
    
    1. 在组件中,您可以使用以下内容:
            async asyncData({app}) {
                    let x = await app.$forumAxios.get("/forum/blah.json");
    

    你当然可以使用 process.env 属性来代替硬编码的 URL。

    这将命中https://other.domain.com/blah.json

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 1970-01-01
      • 2019-06-30
      • 2020-09-29
      • 2022-01-19
      • 2020-09-24
      • 2018-06-03
      • 2021-05-09
      • 2018-11-29
      相关资源
      最近更新 更多