How to set API path in vue.config.js for production?

ierdna picture ierdna · Jul 18, 2018 · Viewed 12.4k times · Source

I'm using vue cli3 for setup. I already have devServer api set up as such in vue.config.js file:

devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:1888/apps/test/mainapp.php/',
            changeOrigin: true,
        },
    },
}

I also need to set path 'https://server/myapp/main.php/' as the production API path, but I can't seem to find any info in the documentation on how to do it. Any help is appreciated.

Brief example of what i'm doing in code:

methods: {
    login() {
        this.axios.post('/api/test')
            .then((resp) => {
                console.log(resp);
            })
            .catch(() => {
                console.log('err:' , err);
            });
    },
},

Answer

Ohgodwhy picture Ohgodwhy · Jul 18, 2018

Your devServer does not run when you execute yarn/npm run build. You are only being supplied with the transpiled javascript to be served. You'll need to change your URL in your .env files.

Development:

.env

VUE_APP_API_ENDPOINT = '/api'

Production:

.env.production

VUE_APP_API_ENDPOINT ='https://server/myapp/main.php'

Then your XHR Request library should be using these environment variables when making requests, such as with axios:

axios[method](process.env.VUE_APP_API_ENDPOINT, data)

Where method would be GET/POST/PUT/DELETE.

Do note that you will be restricted to the rules put in place by Cross-Origin-Resource-Sharing. If your server is not allowing the URL serving your Vue.js pages, you'll need to open it up.

You don't need to make any changes to your devServer configuration because your .env will now declare xhr requests sent to /api which will still proxy for you.