ierdna
ierdna

Reputation: 6293

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

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);
            });
    },
},

Upvotes: 12

Views: 19375

Answers (3)

Arun Raj
Arun Raj

Reputation: 263

If your vue-cli version is higher than 3.x, then add your

development variables in .env file

production variables in .env.production file

Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access them in your application code: console.log(process.env.VUE_APP_SECRET) Vue Doc

Upvotes: 0

billychan
billychan

Reputation: 59

You are using axios in your code, so you can try:

// service.js
import axios from 'axios';
axios.defaults.baseURL = 'https://server/myapp/main.php/';
export default axios;

// main.js
Vue.prototype.$axios = axios;

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

Then every request would send with the default baseUrl you set.

Check out more options for axios

Upvotes: 4

Ohgodwhy
Ohgodwhy

Reputation: 50798

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.

Upvotes: 14

Related Questions