base url is not working

gomezmark
0
gomezmark
commented 2 years ago

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

0
SnooHD
5
SnooHD
commented 2 years ago

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

0
gomezmark
0
gomezmark
commented 2 years ago

Yes sir,

On the top,
I declared it

var environment = {
 API_URL = 'api location' 
} 

module.exports = {...} 
0
mingliao
5
mingliao
commented 2 years ago

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
})
0
mingliao
5
mingliao
commented 2 years ago

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

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

*api location *with a space

0
gomezmark
0
gomezmark
commented 2 years ago

@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
0
SnooHD
5
SnooHD
commented 2 years ago

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/'
  },
0
gomezmark
0
gomezmark
commented 2 years ago

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
                            }
                        }
                    );
}
0
SnooHD
5
SnooHD
commented 2 years ago

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.

0
gomezmark
0
gomezmark
commented 2 years ago

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?

0
SnooHD
5
SnooHD
commented 2 years ago

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 :)

0
forteleaf
0
forteleaf
commented a year ago

in nuxt.config.js

use like this.

modules: [
  ['@nuxtjs/axios', {
    baseURL: 'http://localhost:8000'
  }]
],
0
begueradj
40
begueradj
commented a year ago

@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)

0
fanvyr
0
fanvyr
commented a year ago

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

0
begueradj
40
begueradj
commented a year ago

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

0
metadeck
0
metadeck
commented 10 months ago

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

0
hoanghiep1x0
0
hoanghiep1x0
commented 8 months ago

I had a similar problem.
My resolution step is as follows:
Delete folder .nuxt + remove cache in browser
Changer
` axios: { baseURL: 'http: // localhost: 8080 / api' } `
It works as expected. Before that, I tried a lot of ways like community tutorials but not effective.

0
eiva
0
eiva
commented 7 months ago

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?

0
begueradj
40
begueradj
commented 7 months ago

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

0
eiva
0
eiva
commented 7 months ago

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

0
Informations
QuestionUnresolved
#c118 - Created 2 years ago