简体   繁体   中英

CORS axios Nuxt.js

I'm using an API with my Nuxt, here is my nuxt.config.js to allow the requests :

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

On a specific page of my app, I need to send requests to another API from another domain. I'm using axios direclty in this Vue component :

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

As response, I obtain CORS error. Can I allow multiple API in my config ?

If you mean being able to access APIs under different URLs, AFAIK it's not possible out of the box. We tried adding proxy to different targets, but it only worked on client side, not during SSR.

What we ended up doing is having the default axios instance for our main API, and creating a plugin that creates extra axios instances for our other APIs for SSR.

  1. Add extra "suburl" to proxy - this sorts out client side and means no CORS issues.
    proxy: {
        '/forum/': {
            target: 'https://other.domain.com/',
            pathRewrite: {'^/forum/': '/'}
        },
        '/api/': ...
    },
  1. For SSR to work, axios should hit directly the other 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. In components, you can then use something like:
        async asyncData({app}) {
                let x = await app.$forumAxios.get("/forum/blah.json");

You can use process.env prop of course instead of hardcoded URL.

This will hit https://other.domain.com/blah.json .

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