Vue.js, using fetch() on localhost

I recently started out using this popular framework Vue.js.

By the time I started using fetch() one of my components I ran into my first problem that put my Google skills to test. 😀

The fetch()-problem in action

While the distributed version on https://martinhirsch.de worked like a charm, running npm run serve on localhost resulted in an error.

// We're sorry but mhirsch doesn't work properly without JavaScript enabled. Please enable it to continue.

Having spent my last five years mostly in the backend and a proprietary frontend I have little to no knowledge in setting up a frontend project. During my Google session the term CORS showed up and led me to this page: https://medium.com/swlh/avoiding-cors-errors-on-localhost-in-2020-5a656ed8cefa.
The first suggestion was to use the proxy settings in Create React App.

So I looked up how to do it in Vue.js.

If your frontend app and the backend API server are not running on the same host, you will need to proxy API requests to the API server during development.

https://cli.vuejs.org/config/#devserver-proxy

I did not even have a backend API server yet and tried it anyway but I changed the suggested port from 4000 to 8080 and it works like a charm.

// vue.config.js

module.exports = {
  devServer: {
    proxy: 'http://localhost:8080'
  }
}

I don’t know why it doesn’t work without the proxy setup but the day I find out I will add an explanation to it.

For now: It helps me develop on localhost and might help you.

Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *