Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt Axios Dynamic url

I manage to learn nuxt by using following tutorial

https://scotch.io/tutorials/implementing-authentication-in-nuxtjs-app

In the tutorial, it show that

axios: {
  baseURL: 'http://127.0.0.1:3000/api'
},

it is point to localhost, it is not a problem for my development,

but when come to deployment, how do I change the URL based on the browser URL,

if the system use in LAN, it will be 192.168.8.1:3000/api

if the system use at outside, it will be example.com:3000/api

On the other hand, Currently i using adonuxt (adonis + nuxt), both listen on same port (3000).

In future, I might separate it to server(3333) and client(3000)

Therefore the api links will be

localhost:3333/api

192.168.8.1:3333/api

example.com:3333/api

How do I achieve dynamic api url based on browser and switch port?

like image 277
Geoffrey Lee Avatar asked Nov 01 '25 19:11

Geoffrey Lee


1 Answers

You don't need baseURL in nuxt.config.js.

Create a plugins/axios.js file first (Look here) and write like this.

export default function({ $axios }) {
  if (process.client) {
    const protocol = window.location.protocol
    const hostname = window.location.hostname
    const port = 8000
    const url = `${protocol}//${hostname}:${port}`
    $axios.defaults.baseURL = url
  }
like image 115
Stella Yu Avatar answered Nov 04 '25 06:11

Stella Yu