簡體   English   中英

CORS axios Nuxt.js

[英]CORS axios Nuxt.js

我在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 direclty:

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

作為響應,我收到CORS錯誤。 我可以在配置中允許多個API嗎?

如果您希望能夠使用不同的URL訪問API,則AFAIK不可能開箱即用。 我們嘗試將代理添加到不同的目標,但是它僅在客戶端起作用,而不是在SSR期間起作用。

我們最終要做的是為我們的主要API使用默認的axios實例,並創建一個為我們的其他SSR API創建額外的axios實例的插件。

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM