[英]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實例的插件。
proxy: {
'/forum/': {
target: 'https://other.domain.com/',
pathRewrite: {'^/forum/': '/'}
},
'/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);
async asyncData({app}) {
let x = await app.$forumAxios.get("/forum/blah.json");
當然,您可以使用process.env道具來代替硬編碼的URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.