Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set proxy for different API server using Nuxt?

So I have 2 applications:

  1. an Adonis API server accessible via http://10.10.120.4:3333

  2. A SSR app using Nuxt.js accessible via http://10.10.120.4:80

The Nuxt.js app is accessible outside using url http://my-website.com. I have axios module with this config

axios: {
    baseURL: '0.0.0.0:3333/api',
    timeout: 5000
}

Now the problem is, when I am requesting data with asyncData it works, but when the request was made from outside asyncData, say created() for example, it throws an error saying the url http:0.0.0.0:3333 is missing which is true since it's already running in the browser and not in the server.

The first solution that I've tried is to change the baseURL of the axios module to this

axios: {
    baseURL: 'http://my-website.com/api',
    timeout: 5000
}

But it seems nuxt server can't find it, so I think the solution is to make proxy and installed @nuxtjs/proxy.

And this is my proxy config in nuxt.config.js

{
  proxy: {
    '/api': 'http://my-website.com:3333',
  }
}

and then I just changed my axios baseURL to

http://my-website.com/api

But again it didn't work.

My question is, how do you deal with this kind of scenario? Accessing different server from browser?

like image 969
wobsoriano Avatar asked Dec 23 '22 18:12

wobsoriano


1 Answers

When using Proxy in a nuxt project you need to remove baseUrl and set proxy to true as seen below.

axios: {
   // Do away with the baseUrl when using proxy
    proxy: true
  },

  proxy: {
    // Simple proxy
    "/api/": {
      target: "https://test.com/",
      pathRewrite: { "^/api/": "" }
    }
  },

when making a call to your endpoint do:

// append /api/ to your endpoints
const data = await $axios.$get('/api/users');

checkout Shealan article

like image 155
Sikiru Abidemi Tiamiyu Avatar answered Dec 28 '22 12:12

Sikiru Abidemi Tiamiyu