Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

base url is not working #134

Closed
gomezmark opened this issue Apr 23, 2018 · 30 comments
Closed

base url is not working #134

gomezmark opened this issue Apr 23, 2018 · 30 comments

Comments

@gomezmark
Copy link

gomezmark commented Apr 23, 2018

Hi,

please help me
on my nuxt.config.js

  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    baseURL: environment.API_URL,
    requestInterceptor: (config, {store}) => {
      config.headers.common['Authorization'] = '';
      config.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;application/json';
      return config
    }
  },

and for my actions

 return  axios.post('/verify/phone', querystring.stringify(phoneData))
                    .then(
                        data => {
                            commit('SET_MOBILE', phoneData);
                            return {
                                valid : true,
                                data  : data
                            }
                        },
                        data => {
                            return {
                                valid : false,
                                data  : data
                            }
                        }
                    );

but for the request
it request on the localhost
http://localhost:3000/verify/phone

This question is available on Nuxt.js community (#c118)
@ghost ghost closed this as completed Apr 23, 2018
@ghost ghost added the cmty:question label Apr 23, 2018
@SnooHD
Copy link

SnooHD commented Apr 23, 2018

Are you sure environment.API_URL is set correctly?
If it returns undefined, this would be the expected behaviour.

@gomezmark
Copy link
Author

Yes sir,

On the top,
I declared it

var environment = {
 API_URL = 'api location' 
} 

module.exports = {...} 

@mingliao
Copy link

why dont you set this env in nuxt.config.js like this:

env: {
    // routerMode: '',
    baseUrl: 'https://easy-mock.com/mock/5add28bf882a6228f0f59696/hd/', //https://easy-mock.com/mock/5add28bf882a6228f0f59696/hd/

  },

and use just like these:

const service = axios.create({
  baseURL: process.env.baseUrl, // api的base_url
  timeout: 5000 // request timeout
})

@mingliao
Copy link

and what I saw you declare the param with a space。

var environment = {
 API_URL = 'api location' //api location
} 

*api location *with a space

@gomezmark
Copy link
Author

@mingliao

this is my full nuxt.config.js

const pkg = require('./package')
const environment = {
  API_URL: '[https://outside_api_location]'
}
console.log(environment.API_URL);
module.exports = {
  mode: 'universal',

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  router: {
    middleware: 'i18n'
  },
  /*
  ** Customize the progress-bar color
  */
  loading: { 
    color: '#ffffff', 
    height : '3px'
  },


  /*
  ** Global CSS
  */
  css: [  
    { rel: 'stylesheet', src : '~/assets/css/helper.css'},
    { rel: 'stylesheet', src : '~/assets/css/font.css'}
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '~/plugins/axios',
    '~/plugins/vue-lodash',
    '~/plugins/vue-moment',
    '~/plugins/i18n',
    { src: '~/plugins/vuelidate'},
    { src: '~/plugins/vue-select', ssr: false },
    '~/plugins/vue-mg-checkbox'

  ],


  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios',
    'bootstrap-vue/nuxt'
  ],
  /*
  ** Axios module configuration
  */
  env: {
    // routerMode: '',
    baseUrl: '[https://outside_api_location]', 
  },
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    baseURL: environment.API_URL,
    credentials : true,
    proxy: false,
    debug: true,
    retry: {
      retries: 3
    },
    requestInterceptor: (config, {store}) => {
      config.headers.common['Authorization'] = '';
      config.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;application/json';
      return config
    }
  },
  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      vendor : [
        'axios',
        'vuelidate'
      ]
    }
  }
}

and for axios plugins/axios

export default function ({ $axios, redirect }) {
  $axios.baseURL = "[https://outside_api_location]";

  $axios.onRequest(config => {
    // eslint-disable-next-line no-console
    console.log('SPY: ' + config.url)

    $axios.defaults.xsrfHeaderName = 'X-CSRF-TOKEN'
  })
}
  • im trying where i could add the base url XD

@SnooHD
Copy link

SnooHD commented Apr 25, 2018

You should declare your baseURL without []
If you want to use it in a plugin, you can read more about how to use the env property here:
https://nuxtjs.org/api/configuration-env/

Personally i just directly set the baseUrl in nuxt.config.js for Axios like so:

axios: {
    baseURL: 'http://localhost:6889/'
  },

@gomezmark
Copy link
Author

gomezmark commented Apr 26, 2018

Hi Sir @SnooHD ,

Yes. without the brackets. I just indicate the bracket for example url.
Sorry for the confusion.

but for store
It looks like this

import Vue from 'vue';
import state from './state';
import axios from 'axios'

const querystring = require('query-string');

const sendVerification = ({ app, commit }, phoneData) => {
   
    return  axios.post('/verify/phone', querystring.stringify(phoneData))
                    .then(
                        data => {
                            commit('SET_MOBILE', phoneData);
                            return {
                                valid : true,
                                data  : data
                            }
                        },
                        data => {
                            return {
                                valid : false,
                                data  : data
                            }
                        }
                    );
}

@SnooHD
Copy link

SnooHD commented Apr 26, 2018

If you do not use arrow functions, you can access axios from this:

const sendVerification = function({ app, commit }, phoneData){
   return this.$axios.$post('/verify/phone').then...
}

You can find an example here:
https://axios.nuxtjs.org/usage.html#store-actions

This way you do not have to use axios as a plugin.

@gomezmark
Copy link
Author

Hi @SnooHD,

Thank you!
It's working now. :)

I need some advice with this one

return  this.$axios.$post('/login/otp', post)
                    .then(
                        data => {
                            Cookie.set('token', data.data.user.token);
                            Cookie.set('uid', data.data.user.userid);
                            
                            commit('SET_AUTH',{
                                token : data.data.user.token,
                                id    : data.data.user.userid
                            });

                            // dispatch user information from profile
                            console.log(this.$axios)
                            this.dispatch('profile/getUserDetails',{},{root: true, credentials : true});
                        },
                    );

I set the cookie
but when executing the getUserDetails the token was null

on my plugins/axios

export default function ({ $axios, redirect }) {
    let __token = Cookie.get("token");
    $axios.defaults.headers.common.Authorize = __token;
    
    $axios.onRequest(config => {
     })
  
    $axios.onError(error => {
      
        }
    });
  }

Am i doing right?

@SnooHD
Copy link

SnooHD commented Apr 27, 2018

Why are you not using this.$auth.loginWith ??
It sets the token and cookie for you, then fetches and sets the user details (on this.$auth.user).
Check the example!

Demo:
https://github.com/nuxt-community/auth-module/tree/dev/examples/demo

Api:
https://github.com/nuxt-community/auth-module/tree/dev/examples/api

Good luck :)

@forteleaf
Copy link

forteleaf commented Jul 4, 2018

in nuxt.config.js

use like this.

modules: [
  ['@nuxtjs/axios', {
    baseURL: 'http://localhost:8000'
  }]
],

@begueradj
Copy link

@forteleaf That is the issue: the owner of the post sees that axios sends GET requests to localhost instead of the URL he defined with baseURL configuration key. And actually I have the same issue (I opened a bug about it)

@fanvyr
Copy link

fanvyr commented Dec 26, 2018

@begueradj got the same issue. do you have a solution for that?

@begueradj
Copy link

The solution I opted for was just to declared the URL variable on the page I needed. I know this is not clean, but that is the deal with Nuxt.js @fanvyr

@metadeck
Copy link

Just double check that the variable is named baseURL rather than baseUrl. That one got me for a while.

@hoanghiep1x0

This comment has been minimized.

@eiva
Copy link

eiva commented May 16, 2019

Why it could not automatically guess base url, like just axios doing itself?
I can have service deployed in different environments(hosts): so how should I set "baseURL" to work with this?

@begueradj
Copy link

Well, the bug issuer did not write baseUrl. So is the case with most other contributors here, but they faced the bug.
In my case, I can not reproduce this issue anymore, but I remember I faced it in previous Nuxt.js versions

@eiva
Copy link

eiva commented May 16, 2019

But actually, I have this problem. As a begginer in nuxt, I tried to use nuxt-axios and it does not work. I spent time looking on how to configure it if I dont have "hardcoded" host...
And I failed.
This is more strange that if I use just axios - it works out of the box.
Maybe somebody knows how to make nuxt-axios work in such situations?
Upd:
Actually, I found the solution:

  axios: {
    baseURL: '/'
  }

Make it works

@felipeblini
Copy link

in nuxt.config.js, instead of:

modules: [ '@nuxtjs/axios', ], axios: { baseURL: 'https://yourapi.com' }

use it:

modules: [ ['@nuxtjs/axios', { baseURL: 'https://yourapi.com' }] ],

@haixiangyan
Copy link

Just double check that the variable is named baseURL rather than baseUrl. That one got me for a while.

This is AWESOME! Now what I am sure is that I am blind haha 🤣

@trainoasis
Copy link

None of the above works unfortunately. NuxtJS/Axios, all request stay localhost instead of using the value in baseURL.

@Sjoerd
Copy link

Sjoerd commented Dec 12, 2020

use this.$axios instead of axios

@OFK0
Copy link

OFK0 commented Dec 15, 2020

I have a simple solution...
create plugins/axios.js file

export default function ({ $axios, $toast, store, redirect }) {
    $axios.onRequest((config) => {
        config.url = '/api/' + config.url
        // ...
     }
}

http://localhost:3000/api/ --> http://localhost:8080/
edit: I have a proxy setting

it is fixed for me, I tried other solutions but only this working...

@bartek88
Copy link

I had the same issue. The solution for me was:

  1. in nuxt.config.js add axios: { baseURL: "your_url", },
  2. in action use this.$axios. So for example:
    this.$axios.get("/something").then((res) => commit("doSomething", res))

This will send a request to your_url/something. And because we are using this.$axios we don't need to import axios.

@darrenchiu
Copy link

Still not working until today. Can anyone share shred some light from this. This is crucial for any apps i believe?

@trainoasis
Copy link

trainoasis commented Jun 8, 2021

@darrenchiu I can share what works for me in one of our projects, if it helps:

package.json:

"@nuxtjs/axios": "^5.12.2",
"nuxt": "^2.14.6",

nuxt.config.js:

axios: {
    baseURL: 'YOUR_API.COM'
    credentials: true,
    https: true
  },

and for example the below in a component makes a request to YOUR_API.COM/orders

this.$axios.get('orders', { params: { app_id: this.getters.appId } })
      .then((res) => {
        commit('SET_ORDERS', res.data.data)
        commit('SET_LINKS', res.data.links)
        commit('SET_META', res.data.meta)
      })
      .catch((error) => {
        this.$handleErrorResponse(error)
      })

You CAN override this though with, for example:

this.$axios({ url: 'data/contact.json', baseURL: window.location.origin, method: 'GET' })

@dotsimplify
Copy link

i had same issue , after 45 minutes headache and googling I get to know what I was doing wrong

const instance = axios.create({
baseUrl : process.env.BASE_URL
})

which was incorrect ........ it must be baseURL not baseUrl

please check this spelling mistake

thanks

@DrBronsy
Copy link

DrBronsy commented Sep 9, 2021

Just double check that the variable is named baseURL rather than baseUrl. That one got me for a while.

БЛяяяяяяяяяяяяяяяяя ть

@AndrianD
Copy link

AndrianD commented Feb 27, 2022

which was incorrect ........ it must be baseURL not baseUrl

@dotsimplify : You save my life, thanks a lot!!

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests