How to set API path in vue.config.js for production?
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.
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