Repository axios-module

adrianoresende

adrianoresende resolved the question #c155

axios-module • 3 days ago

Syntax Error: await is a reserved word

Is right! Await need async to work.

async nameMethod() {
    await Promise(...);
}
woodgates

woodgates posted a new question

axios-module • 4 days ago

Syntax Error: await is a reserved word

Hi.

I'm using nuxt with Adonis + Vuetify. This is my Feeds.vue code:

<template> ...</template>
<script>
export default {
  data(){
    return {
    }
  },
  asyncData (app) {
    const res = await app.$axios.$get('api.v1/feeds')
    return { feeds: res}
  },
}
</script>

with this I'm getting a "Syntax Error: await is a reserved word"

i solved with

 async asyncData (app) {
    const res = await app.$axios.$get('api.v1/feeds')
    return { feeds: res}
  },

Can you tell me if this is right, and if so, please correct the docs?

mattwaler

mattwaler posted a new question

axios-module • 4 days ago

How to use @nuxtjs/axios for async routes generation instead of axios

Currently I am unable to use the nuxt-axios module to generate dynamic routes in my nuxt.config.js file.

The only way I have been successful in doing this is by installing both axios and nuxtjs/axios and using the standalone axios package in my nuxt.config.js file. Screenshots attached.

I would like to lower my dependencies and not need both packages of axios, is there a way to use the axios module in my nuxt.config.js file?

Screenshots
Screen Shot 2018-08-16 at 12.33.29 PM.jpg
Screen Shot 2018-08-16 at 12.33.25 PM.jpg

itswadesh

itswadesh posted a new question

axios-module • 13 days ago

dev vs prod mode for proxy module

The following code works perfect in development mode

axios: { proxy: true, credentials: true, }, proxy: { '/api': 'https://admin.arialshop.com' }

When I build the app using npm run build the proxy is missing. I am doing anything wrong?

jericopulvera

jericopulvera posted a new question

axios-module • 15 days ago

axios calls to take at least 500 millisecond [FEATURE REQUEST]

Hi, guys is it easy to add this kind of feature?

https://gist.github.com/adamwathan/babd10ed0e971404c5d8a86358d01b61

jimliang

jimliang posted a new bug report

axios-module • 18 days ago

bug browserBaseURL not change when I change env

Version

v5.1.0

Reproduction link

https://jsfiddle.net/

Steps to reproduce

In src("@nuxtjs/axios": "^5.3.1",), options use <%= =%> inject into the code:

baseURL : process.browser
      ? '<%= options.browserBaseURL %>'
      : (process.env._AXIOS_BASE_URL_ || '<%= options.baseURL %>'),

it will generate:

    baseURL : process.browser
      ? 'http://localhost:3000/'
      : (process.env._AXIOS_BASE_URL_ || 'http://localhost:3000/'),

Now I change env API_URL_BROWSER, but browserBaseURL will not change.
I must rebuild to fix it.

What is expected ?

browserBaseURL can change depend on APIURLBROWSER without rebuild

What is actually happening?

browserBaseURL not change

jimliang

jimliang posted a new question

axios-module • 18 days ago

browserBaseURL not change when I change env

In src, options use <%= =%> inject into the code:

baseURL : process.browser
      ? '<%= options.browserBaseURL %>'
      : (process.env._AXIOS_BASE_URL_ || '<%= options.baseURL %>'),

it will generate:

    baseURL : process.browser
      ? 'http://localhost:3000/'
      : (process.env._AXIOS_BASE_URL_ || 'http://localhost:3000/'),

Now I change env API_URL_BROWSER, but browserBaseURL will not change.
I must rebuild to fix it.

wumble

wumble posted a new question

axios-module • a month ago

Return Response in Request Interceptor

i have saved a response in a sessionStorage object on Response Interceptor. How would i return this in a Request Interceptor?
I would like to return this saved response for requests that are made shortly after each other.

my Response Interceptor:
// intercept response // save response as session storage item $axios.onResponse(response => { sessionStorage.setItem( response.request.responseURL, JSON.stringify({ time: Date.now(), response, }), ); });

and my Request Interceptor so far:
// look if same request was made in last x seconds $axios.onRequest(config => { let item = null; let url =${config.baseURL}${config.url}; const params = Object.entries(config.params).map(([key, val]) =>${key}=${val}).join('&'); url =${url}?${params}; if (item = sessionStorage.getItem(url)) { // return JSON.parse(item).response } else { // do nothing } });

dysol

dysol posted a new question

axios-module • a month ago

Env var undefined in plugins/axios.js

This is the setup

Install @nuxtjs/dotenv module.

Inside my nuxt.config.js

env property is an empty object. Reason being, i used dotenv module to load my env vars in dev.

  • In production, for example: heroku -> declare an env variable - API_TOKEN=abcde

  • In plugins/axios.js

export default function({ env }) {

console.log(env);

console.log(process.env.API_TOKEN);
}

Console logging env should returned undefined

console logging process.env.API_TOKEN returned 'abcde'.

My question is - why didn't nuxt load heroku env vars ?

zhujunel

zhujunel posted a new question

axios-module • a month ago

Response interceptor using extend @nuxtjs/axios

import { Toast } from 'vant'; export default function ({ $axios, redirect }) { $axios.defaults.timeout = 5000 $axios.onRequest(config => { console.log('Making request to ' + config.url) }) $axios.onResponse(response => { console.log('Making response to ' + response.status) console.log(response.data) if (response.data.status !== 0) { Toast(response.data.error_info) } }) $axios.onError(error => { const code = parseInt(error.response && error.response.status) if (code === 400) { redirect('/400') } }) }
Why does it have no effect?

agcty

agcty posted a new question

axios-module • a month ago

How to dispatch an axios action and catch error in vue component?

I have a login method in my store like this:

export const actions = {
  login(vuexContext, authData) {
    //post user credentials to server
    return (
      this.$axios
        .$post("/auth/token.json", {
         ...authData
        })
        //save userId, token, tokenExpiry, refreshToken and refreshTokenExpiry
        .then(result => {
          vuexContext.dispatch("saveTokenData", result);
          console.log("[AUTH] LOGIN SUCCESSFUL");
        })
        .catch(error => {
          console.log("LOGIN AUTH POST", error.response);
        })
    );

Now I want to dispatch this action in a vue component like this:

methods: {
    onSubmit()
        this.$store
          .dispatch("auth/login", {
            ...this.authData
          })
         .then(() => this.$router.push("/"))
         .catch(this.danger("Error while logging in"));
   }

However, even if there is an error (401, 400) the then block in the method gets executed and if there's no error, the catch block gets executed. Is this the right usage pattern I'm using?

stecapra

stecapra posted a new question

axios-module • a month ago

Cannot get the cookies in middleware http request

Hi,
i'm trying to implement an auth middleware, with an http request to my backend server the check if there is a cookie with a session id, but every time i make the request in the middleware, the result is always like the user is not logged in.
Instead, if i make the same request in mounted function of my page, everything works perfect.
I searched and found this topic https://cmty.app/nuxt/nuxt.js/issues/c401 where it said that the axios module has a built in fix method, but for me it doesn't work , and i already posted a comment there, but since is closed i think that no one saw my reply.
Why there is still this problem?

Thank you in advance

daskyrk

daskyrk posted a new question

axios-module • a month ago

helper only trigger in server render

this is part of my config:

  modules: ['@nuxtjs/axios'],
  axios: {
    // proxy: true,
    baseURL: 'http://localhost:8000/api',
    browserBaseURL: IS_DEV
      ? 'http://localhost:8000/api'
      : 'https://lijun.space/api',
    // prefix: '/api', // it not work
    credentials: true,
    // debug: true,
  },

this is plugins/axios.js:

export default function({ $axios, store }) {
  $axios.onRequest(config => {
    console.log('on request:'); // only log in server render
    store.commit('START_FETCH', config.url.substring(1));
  });
}

it is strange that onRequest only trigger in server render, when i start a request in page, it will no output any log.

hardikshah91

hardikshah91 posted a new question

axios-module • a month ago

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I'm using Nuxt-axios module with the proxy.

For Error handling, I have common code in

Plugins/axios.js

export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) {
  $axios.onRequest(config => {
  if (app.$cookies.get('at') && app.$cookies.get('rt') && config.url != '/post_login/') {
      config.headers.common['Authorization'] = `Bearer ${app.$cookies.get('at')}`;
    }
  });

  $axios.onResponseError(err => {
    const code = parseInt(err.response && err.response.status)

    let originalRequest = err.config;

    if (code === 401) {
      originalRequest.__isRetryRequest = true;

      store
        .dispatch('LOGIN', { grant_type: 'refresh_token', refresh_token: app.$cookies.get('rt')})
        .then(res => {
          originalRequest.headers['Authorization'] = 'Bearer ' + app.$cookies.get('at');
          return app.$axios(originalRequest);
        })
        .catch(error => {
          console.log(error);
        });
    }

    // code for 422 error
    if (code == 422) {
      throw err.response;
    }

  });
}

On my page folder index page

Pages/index.vue

<template>
  <section>Component data</section>
</template>

<script type="text/javascript">
export default {
  async asyncData({ route, store }) {
    await store.dispatch('GET_BANNERS');
  }
}
</script>

All the API calls are in a stroes/actions.js file.

Now the question is when I refresh the page index.vue first API request will hit and get the response if successful. But now if on first request( 'GET_BANNERS' ) from asyncData and it gets 401 error unauthorized then I'm getting below error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

how can I resolve this?

few more questions:

1) When I'm writing common error code in axios, original request on which I have received 401 how can I set data to store again(which we normally do from actions file)?

2) can anyone help with best practice to attach authorization headers and error handle for 400,401,422, etc..

kindles

kindles posted a new bug report

axios-module • 2 months ago

bug Authorization header doesn't exist

Version

v5.1.0

Reproduction link

https://gist.github.com/kindles/d89233807efa0a5090eb36e7536bed62

Steps to reproduce

Use the module in asyncData() and mounted(), in the first method It works (the request has an header authorization) and in the second method It doesn't work (the request doesn't have an header authorization).

What is expected ?

this.$axios.defaults.headers.common['Authorization'] = accessToken; and this.$axios.setHeader('Authorization', '123') set a header when I use the module in a mounted function.

What is actually happening?

this.$axios.defaults.headers.common['Authorization'] = accessToken; and this.$axios.setHeader('Authorization', '123') doesn't set an header when I use the module in a mounted function.

liuhuanhui

liuhuanhui posted a new question

axios-module • 2 months ago

After configuring the login successfully, jump to the /user page but after the success, there is no jump, go to / home page.

config:

auth: {
    redirect: {
      login: '/login',
      callback: '/login',
      user: '/register',
      // logout: '/login'
    },
    strategies: {
      local: {
        endpoints: {
          token_type:'',
          login: { url: '/v1/login', method: 'post', propertyName: 'data' },
          // logout: { url: '/api/auth/logout', method: 'post' },
          user: { url: '/v1/user/info/base', method: 'get', propertyName: 'data' },
        },
        tokenRequired: true,
        tokenType: '',
      }
    }
  },

login:

  let { code, msg, data } = await loginService({
              userAccount: this._.trim(this.frm.userid),
              userPwd: this.md5(this.frm.password)
            })
            if (code === 0) {
              this.$auth.setToken('local', data)

              await this.$auth.fetchUser().then(data => {
                console.log('login suces', data)
              })
            } else if (code === 20002) {
              this.showVerification = true
            } else {
              throw new Error(msg)
            }
Bombay

Bombay posted a new question

axios-module • 2 months ago

How to handle error in plugin?

Hi. How to handle error in plugin?

export default function ({ $axios, store, error }) {
  $axios
    .onError(apiError => {
      error({statusCode: '403', message: 'test'})
    })
}

image

redirect is working. but error is not work.
thank you for great module.

jeck5895

jeck5895 posted a new question

axios-module • 2 months ago

this.$axios.$get gets undefined on actions that's in a separated file (namespaced)

actions.js
export default { fetchCities: ({commit}, payload) => { var self = this; return new Promise ((resolve, reject) => { this.$axios.$get('http://api.foodpaket.com/api/v1/web/cities') .then(response => { commit('setCities', response.data); resolve(context) }) .catch(err => { console.log(err) reject(err); }) }) }, }

jeck5895

jeck5895 posted a new question

axios-module • 2 months ago

.onResponse is not a function

Hello I just need help about this one. Cant found related about it
image

daskyrk

daskyrk posted a new question

axios-module • 2 months ago

option `prefix` not work

prefix config not work, and not see any code about prefix in plugin.template.js, is doc out of date or it's a bug ?