How to use a local API with a Vue app served at a different port?

Viewed 4214

I'm helping someone get a Django + Vue app up and running and one issue we're running into is how to have the Vue app hot-reload while also being able to interact with the local Django server.

In production the Django server will serve the Vue app, and npm run build puts the Vue app's assets in the Django project's templates/ and static/ folders.

When we run the Django server (python manage.py runserver), the server is running at localhost:8000. When we run npm run serve (to get the benefits of hot reloading), the Vue app is being served at localhost:8080. If I do a GET request from the Vue app to /exampleEndpoint, it goes to localhost:8080/exampleEndpoint, thus not hitting the Django server.

What's the proper way to have the Vue app work with the Django app?

2 Answers

If you are using axios then you can do:

axios.defaults.baseURL = '//localhost:8000/';

Omitting http/s and just starting with double slash will make the current protocol be inherited into the url.

This will result in axios.post('/api/example') requesting http(s)://localhost:8000/api/example as long as all your request URI's start with a single slash.

Edit: You will need to allow CORS Headers. There is a package django-cors-headers for this. It's very easy to use and works just fine: https://github.com/ottoyiu/django-cors-headers/

The solution we ended up going with (which isn't really answering this question's title but solves the underlying problem) was to not use the vue-cli hot reload server but rather have changes to the front-end's files trigger npm run build, so that the front-end app would be served by the Django server (as it would be in production). To accomplish this I installed the "npm-watch" package and have "npm run watch" watch all .vue, .scss, and .js files in the /src directory. The commit is below.

enter image description here

Related