Activities

filipkisic

filipkisic posted a new question

axios-module •

Axios self signed certificate error in asyncData and nuxtServerInit

I am working on a project and I am using nuxt for it. API calls are being made to node.js server over https, and since everything is in my local development, I am using self signed certificates.

When I try to make axios call from asyncData, I receive

ERROR  self signed certificate                                                                                                                                           
at TLSSocket.onConnectSecure (_tls_wrap.js:1049:34)
at TLSSocket.emit (events.js:182:13)
at TLSSocket.EventEmitter.emit (domain.js:442:20)
at TLSSocket._finishInit (_tls_wrap.js:631:8)`

Same error shows when i try to make axios call from nuxtServerInit . Identical call made from methods and called with @click gets the data and works. Also, other calls in store actions also work without issues.

Is there a reason why this calls don't work, and also, is there a way to make axios calls as described above?

this doesn't work:

async asyncData(context) {
    let result = await context.app.$axios.$get("/item", {
      headers: {
       "x-auth": context.store.getters["login/getToken"]
  }
  });       
  console.log("item: ", result.item);
}

and this does work without problems:

methods: {
async getItem() {
try {
  let result = await this.$axios.$get("/item", {
    headers: {
      "x-auth": this.$store.getters["login/getToken"]
    }
  });      
  console.log("item : ", result.item);
  } catch (e) {
  console.log(e);
  }
 }
}

Thank you for help

papakay

papakay posted a new question

axios-module •

asyncData takes a longer time to return data.

Hi, I really want to commend the great work done on this package.

Please I have a page that takes over 20 seconds to load and that has been a great concern to me. The page is just a form but it gets the form data from an API endpoint. With the asyncData method, the page takes more than 20 seconds. I've also tested the endpoint to confirm if that was the problem, but the endpoint takes less than 0.7 second to return data. This is what my async data looks like

async asyncData({ $axios }) {
    try {
      const response = await $axios.$get("v1/account/me");
      return {
        user: response.data.user
      };
    } catch (e) {
      return {
        user: null
      };
    }
  },

Please what are mine doing wrong?

matamune94

matamune94 posted a new question

axios-module •

share a method of use axios globally standard for nuxtjs?

i want use it for all components and pages and my config present :

~/plugins/axios

import axios from 'axios'

export default axios.create({
baseURL: 'http://127.0.0.1:3001/'
})

but with this way , i must import axios from '~/plugins/axios' in components and pages i want use something choise for like this

this.$axios.post('url',data).then(res=>{
// do something in here
}).catch({
// do something in here
})

and no need import more axios

EinYs

EinYs posted a new bug report

axios-module •

bug Solved

Version

5.0.0

Reproduction link

https://github.com/EinYs/nuxt-axiosTest

Steps to reproduce

  1. excute 'npm run dev'
  2. go to http://localhost:3000

What is expected ?

index page to be opened

What is actually happening?

Memory leak and crash

Additional comments?

Tested version 5.0.0 ,5.3.2 ,5.3.4 and that all got a memory leak error. The linked is with v5.3.2

If nuxt/axios module and config is removed from nuxt.config.js file, app will not make errors.

my nodejs version is v10.9.0


Attaching my memory crash log

<--- Last few GCs --->

[18052:000001B62E87F9E0] 70021 ms: Mark-sweep 1353.0 (1456.9) -> 1352.9 (1456.9) MB, 1358.3 / 0.6 ms (average mu = 0.082, current mu = 0.000) allocation failure GC in old space requested
[18052:000001B62E87F9E0] 71405 ms: Mark-sweep 1352.9 (1456.9) -> 1352.7 (1426.4) MB, 1383.5 / 0.8 ms (average mu = 0.042, current mu = 0.001) last resort GC in old space requested

<--- JS stacktrace --->

==== JS stack trace =========================================

0: ExitFrame [pc: 0000004F69EDC6C1]

Security context: 0x03abdc49e549 <JSObject>
1: _extend [0000017716F12E01] [util.js:~1253] [pc=0000004F6A511ABF](this=0x01a11f203f89 <Object map = 000000536F8B26C1>,target=0x0177de472739 <Object map = 000000536F882571>,source=0x0177de473e71 <Object map = 000002011DF0F301>)
2: new constructor(aka Socket) [0000021000907DF1] [net.js:239] [bytecode=0000017716F42EC1 offset=118](this=0x0177de472641…

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
1: 00007FF69D733D05
2: 00007FF69D70DD46
3: 00007FF69D70E610
4: 00007FF69DB748DE
5: 00007FF69DB7480F
6: 00007FF69DAC01A4
7: 00007FF69DAB6747
8: 00007FF69DAB4CBC
9: 00007FF69DAB4155
10: 00007FF69DABDDA4
11: 00007FF69DBE3388
12: 00007FF69DBE964A
13: 00007FF69DAF0B94
14: 00007FF69D9C9B0E
15: 00007FF69D9C9C66
16: 00007FF69D9CBE1B
17: 00007FF69D9BABD4
18: 00007FF69D9CB209
19: 00007FF69D99816E
20: 00007FF69D9BED41
21: 00007FF69DC62B71
22: 00007FF69DC65C08
23: 0000004F69EDC6C1
npm ERR! code ELIFECYCLE
npm ERR! errno 134
npm ERR! [email protected] dev: node api/server.js
npm ERR! Exit status 134
npm ERR!
npm ERR! Failed at the [email protected] dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

renishdeveloper

renishdeveloper posted a new question

axios-module •

How to send dunamic key ,value pair while calling POST api in react native

I'm calling the API like this
const data = await axios.post(url, {
key : value,
})
.then(function (response) {
console.warn(response);
})
.catch(function (error) {
console.log('exios erro=>', error);
});
It works fine ,but I want to assign the key from the state ,when i going to write this.state.key instead of key it shows error "Unhandled Promise Rejection".
How to assign the dynamic key while calling API using Axios.

SanBen

SanBen posted a new question

axios-module •

Can I access the Cancel class from the axios-module?

I am unable to access the Cancel class to cancel a response inside an interceptor.
Digging through the source code I think it's not exposed?

Is it possible to create a new Cancel object some other way?

What I want to achieve is outlined here -> https://github.com/axios/axios/issues/583#issuecomment-265934552

I want to be able to cancel a response like this:

axios.interceptors.response.use(function (response) { throw new axios.Cancel('Operation canceled by the user.'); }, function (error) { return Promise.reject(error); });

zhaojunlike

zhaojunlike posted a new bug report

axios-module •

bug I can't perform penument.resolve in the error blocker, which will cause the app direct crash

Version

v5.1.0

Reproduction link

https://github.com/nuxt-community/axios-module/tree/dev/lib

Steps to reproduce

I can't perform penument.resolve in the error blocker, which will cause the app direct crash;

hello,I want an axios interceptor like onError to return custom data after execution, but this can cause the program to crash
image

   $axios.onError((error) => {
        const code = parseInt(error.response && error.response.status);
        const message = (error.response && error.response.data && error.response.data.message) || 'Api请求失败';
        console.error("Api:", error.message, message);
        switch (code) {
            case 500:
                break;
            default:
                break;
        }
        const res = {message: message, ok: false, status: code};
        return res;
    });

What is expected ?

When working directly with axios, this is fine.Because our back-end encapsulates the data differently, we identify success by ok

What is actually happening?

app crashed

zhaojunlike

zhaojunlike posted a new question

axios-module •

app crashed - waiting for file changes before starting

hello,I want an axios interceptor like onError to return custom data after execution, but this can cause the program to crash
image

  $axios.onError((error) => {
       const code = parseInt(error.response && error.response.status);
       const message = (error.response && error.response.data && error.response.data.message) || 'Api请求失败';
       console.error("Api:", error.message, message);
       switch (code) {
           case 500:
               break;
           default:
               break;
       }
       const res = {message: message, ok: false, status: code};
       return res;
   });
cvharris

cvharris posted a new question

axios-module •

Can I import/require axios from the nuxt module?

I have an Express app and I'd like to use axios to make server-side API calls, apart from Nuxt. Do I have to add axios as it's own dependency or is there a way to const axios = require('@nuxtjs/axios').axios or something similar?

Saw this issue and comment by @clarkdo which hinted that it was possible but may not be implemented

TheNoim

TheNoim posted a new question

axios-module •

setToken nuxtServerInit

I read https://github.com/nuxt-community/modules/issues/89 and some people had the same problem like I have now and it was never resolved.
How can I set the token in nuxtServerInit and don't need to set it again on client side?

ilrock

ilrock posted a new question

axios-module •

Extending axios not working

Hey there,

I have a nuxt app with the following cofiguration:

plugins: [
//'~/plugins/vuetify.js'
{ src: '~/plugins/components' },
{ src: '~/plugins/vue-upload', ssr: false },
{ src: '~/plugins/vue-trix', ssr: false },
{ src: '~/plugins/vue-notification' },
{ src: '~/plugins/stripe-checkout', ssr: false },
{ src: '~/plugins/vue-colors', ssr: false },
{ src: '~/plugins/axios' },
],

/*
** Nuxt.js modules
*/
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'@nuxtjs/axios',
['nuxt-log', logOptions],
['@nuxtjs/moment'],
],

As you can see, I added a plugin called axios. The file plugins/axios looks like so:

export default ({ $axios, store }) => {
// $axios.defaults.baseURL = 'https://api.com/api/'

if (process.server) {
return
}

$axios.interceptors.request.use(request => {
// request.baseURL = 'https://api.com/api/'

// Get token from auth.js store
const token = localStorage.getItem('jwtToken')

// Update token axios header
if (localStorage.getItem('jwtToken')) {
  const token = localStorage.getItem('jwtToken')
  request.headers.common['Authorization'] = `Bearer ${token}`
}
return request

})
}

I'm simply checking whether the jwt token has been saved in the local storage and set the header accordingly. For some reason, this is not working.

No header is actually set before an axios request.

Any idea?

kaloraat

kaloraat posted a new question

axios-module •

$axios.onError is not a function

This code was working find for weeks until today. Now I cant get rid of the error $axios.onError is not a function

export default function({ $axios, store, redirect }) {
    $axios.onError(error => {
        if (error.response.status === 422) {
            store.dispatch("validation/setErrors", error.response.data.errors);
            return redirect("/login");
        }
        return Promise.reject(error);
    });

    $axios.onRequest(config => {
        config.headers["Content-Type"] = "application/json";
        config.headers["Access-Control-Allow-Origin"] = "*";

        store.dispatch("validation/clearErrors");
    });
}
kaloraat

kaloraat posted a new question

axios-module •

$axios.onError is not a function

This issue is also posted in stackoverflow. There were no issues for days using the exact same code. Now all of a sudden I get this error $axios.onError is not a function

What could be wrong?

WangHansen

WangHansen posted a new bug report

axios-module •

bug Axios module doesn't respect config when used in server

Version

v5.1.0

Reproduction link

https://jsfiddle.net/

Steps to reproduce

The axios getting called in asyncData and middlewares do not respect the setting of https true

What is expected ?

to follow the settings and use https

What is actually happening?

used http

yhanwen

yhanwen posted a new question

axios-module •

What's the reason of save baseUrl to process.env._AXIOS_BASE_URL_?

https://github.com/nuxt-community/axios-module/blob/f638dfe23c8351be80ea1d5c02ac4a0caed74511/lib/module.js#L96

While I want to run 2 nuxt instance with axios in single server, last one's config will overwrite the others'.

begueradj

begueradj posted a new bug report

axios-module •

bug baseURL settings do not take effect for axios

Version

v5.1.0

Reproduction link

https://github.com/begueradj/nuxt-axios-baseurl-bug

Steps to reproduce

  1. Clone my repo and change to the resulted directory
  2. Intall the dependencites: yarn install
  3. Launch the server: yarn run dev

What is expected ?

expect the number of displayed posts to be 100.

This means in pages/index.vue, when I have this code:

mounted() {
    axios.get('/posts')
    .then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }

axios should recoginize the baseURL configuration key I set in nuxt.config.js and thus fetch data from http://jsonplaceholder.typicode.com/posts

Here is my nuxt.config.js file content related to axios module:

modules: [
    // Doc: https://github.com/nuxt-community/axios-module#usage
    ['@nuxtjs/axios', {
      baseURL: 'http://jsonplaceholder.typicode.com'
    }]
  ],
  /*
  ** Axios module configuration
  */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
  },

What is actually happening?

  1. The number of displayed posts is 0

  2. axios is trying to send a get request to http://localhost/posts instead of http://jsonplaceholder.typicode.com/posts

manniL

manniL posted a new feature request

axios-module •

idea Don't accept br encoding on Server side

What problem does this feature solve?

Node can't parse brotli natively. Browser can.

That's why axios on server-side will throw up with gibberish characters when it retrieves content from a brotli API.

We should set the appropriate headers to avoid that behavior by default.

manniL

manniL posted a new question

axios-module •

Don't accept br encoding on Server side

Node can't parse brotli natively. Browser can.

That's why axios on server-side will throw up with gibberish characters when it retrieves content from a brotli API.

We should set the appropriate headers to avoid that behavior by default.

Example: https://codesandbox.io/s/m4k3yn7x8

manniL

manniL posted a new question

axios-module •

Don't accept br encoding on Server side

Node can't parse brotli natively. Browser can.

That's why axios on server-side will throw up with gibberish characters when it retrieves content from a brotli API.

We should set the appropriate headers to avoid that behavior by default.

Example: https://codesandbox.io/s/m4k3yn7x8

enzolutions

enzolutions posted a new question

axios-module •

Dynamically change api via request headers

Using nuxt.config.json I could configure a proxy forward to use a backend server for API, for instance

  proxy: {
    '/api/': 'http://localhost:8888'
  },

I am wondering if there is a way that before to call axios.post or axios.get methods I could overwrite temporary the target of the '/api' based on request parameters that allow me to do some logic.

Kind regards