简体   繁体   English

CORS axios Nuxt.js

[英]CORS axios Nuxt.js

I'm using an API with my Nuxt, here is my nuxt.config.js to allow the requests : 我在Nuxt上使用API​​,这是我的nuxt.config.js允许请求:

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. 在我的应用的特定页面上,我需要将请求从另一个域发送到另一个API。 I'm using axios direclty in this Vue component : 我在这个Vue组件中使用axios direclty:

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

As response, I obtain CORS error. 作为响应,我收到CORS错误。 Can I allow multiple API in my config ? 我可以在配置中允许多个API吗?

If you mean being able to access APIs under different URLs, AFAIK it's not possible out of the box. 如果您希望能够使用不同的URL访问API,则AFAIK不可能开箱即用。 We tried adding proxy to different targets, but it only worked on client side, not during SSR. 我们尝试将代理添加到不同的目标,但是它仅在客户端起作用,而不是在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. 我们最终要做的是为我们的主要API使用默认的axios实例,并创建一个为我们的其他SSR API创建额外的axios实例的插件。

  1. Add extra "suburl" to proxy - this sorts out client side and means no CORS issues. 在代理中添加额外的“ suburl”-这样可以解决客户端问题,这意味着没有CORS问题。
    proxy: {
        '/forum/': {
            target: 'https://other.domain.com/',
            pathRewrite: {'^/forum/': '/'}
        },
        '/api/': ...
    },
  1. For SSR to work, axios should hit directly the other API 为了使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. 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. 当然,您可以使用process.env道具来代替硬编码的URL。

This will hit https://other.domain.com/blah.json . 这将访问https://other.domain.com/blah.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM