I'm currently using devServer{proxy:{...}}
in vue.config.js to configure proxy for api calls for avoiding CORS problems in my application. It works fine when I run npm run serve
in localhost.
Now I need to deploy my application to a host, so I run npm run build
, change the url's of my Ajax calls and it's not running... So what I indeed need is to configure my proxy for deployment (build), not for devServer.
What is the correct way to do that?
I've already tried:
server{proxy:{...}}
and build{proxy:{...}}
, but none of them are allowed when running npm run build
.
Thank you!
You can try another approach which is adding API URL's to .env files
If you are using Vue CLI you can create .env.development and .env.production files and put API URL's for development and production like:
.env.development
VUE_APP_API_URL=http://localhost:8080/api
.env.production
VUE_APP_API_URL=http://myapp.com/api
In your project files you can access the variables by putting VUE_APP_ keyword like;
Your file to make api requests
const url = process.env.VUE_APP_API_URL
const res = axios.get(url, config).then (...)
.catch(...)
You can look for more from Vue's official docs
To handle the CORS issue, I can give you some tips.
Vue CLI, by default, will not ship a webserver like the proxy, it will deploy bundled Javascript in a dist/
directory.
/dist
directory, find the instructions here for your provider (S3, Netlify, Firebase) and follow them.You're running into an issue because the proxy is not supposed to be used for production. The proxy Vue CLI is shipping with is webpack-dev-server. It is used by Vue CLI to enable you to serve your Javascript files locally during development.
There are security vulnerabilities if you use webpack-dev-server (aka the proxy) in prod. Don't do it.
Instead, you need to find the hosting provider you're using and follow the instructions here: https://cli.vuejs.org/guide/deployment.html to deploy your application. If your application is personal or can be public, I suggest using Netlify.
For example... In my production setup, we deploy to an AWS S3 bucket and serve content with either AWS Cloudfront CDN or the Fastly CDN. Our API urls are always the production server ones, and we use this setting in the proxy to pass through to our local server
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With