Warm tip: This article is reproduced from stackoverflow.com, please click
axios frontend vue.js

Vue.js based common front-end script on CDN with multiple backends

发布于 2020-04-19 09:46:26

i am designing a common front-end custom components library (vue-components.js) in Vue.js. This library will be hosted on a CDN and there will be applications with different backends and domain names (e.g. Java, .Net, PHP) using this single .js file in CDN to build their front end.

e.g. Front-end for Java application

<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://xyz.s3-aws-domain.com/vue-components.js"></script>
</head>

<body>
//custom vue components called.
<vue-inputbox></vue-inputbox>
<vue-btnsubmit><vue-btnsubmit>
</body>

Assuming that each different application (mix of single page apps and multi page apps) with different backend will call the same centrally hosted vue-components.js, how would the different applications specify their own AXIOS API endpoints to get the input values from the front end.

i am currently exploring custom AXIOS instances but i understand the endpoints would have to be configured centrally as well. Is there a way to let the different backends specify their own endpoints or design such that each application referencing this common cdn vue-components.js file can configure their own API endpoints locally on their own server?

Thank you so much.

Questioner
sir.superstar
Viewed
18
Michal Bieda 2020-02-05 19:19

Sounds like you need something similar to .env files/variables but on the client side.

Each of your backends could generate a simple JS file of common format, for example:

<script>
    window.__env = {
        apiBackend: 'http://some.site/api/1/'
    }
</script>

and then include it before your components from CDN

<head>
    <!-- libs -->
    <script src="env.js"></script>
    <script src="https://xyz.s3-aws-domain.com/vue-components.js"></script>
</head>

and then in your components use this globally available object to create axios instance

// api.js
export const API = axios.create({
    baseURL: __env.apiBackend
})

// in some component
import API from 'api.js'

// in vue component method/action/vuex etc
API
    .post('getSomeData', {id: 123})
    .then(response => {
        // do something with data from http://some.site/api/1/getSomeData
    })