-->

How to set API path in vue.config.js for productio

2020-07-10 08:19发布

问题:

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

回答1:

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.



回答2:

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



回答3:

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