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

Asynchronous support: onRequest/onResponse #482

Open
insell824 opened this issue Mar 15, 2021 · 6 comments · May be fixed by #548
Open

Asynchronous support: onRequest/onResponse #482

insell824 opened this issue Mar 15, 2021 · 6 comments · May be fixed by #548

Comments

@insell824
Copy link

Hi, is it possible to support "async for extensions before and after communication"?

Corresponding part

onRequest(fn) {
this.interceptors.request.use(config => fn(config) || config)
},
onResponse(fn) {
this.interceptors.response.use(response => fn(response) || response)
},

Use Case
We are using JWT of Firebase Authentication. We would like to extend the process of granting "Bearer tokens" for all or specific communications prior to communications. If the JWT has been expired, the method of getIdToken() updates it to make it a valid token before continuing with the request. Here, communication occurs before communication, and asynchronous processing should be required.

How to fix
We have confirmed the operation with the following support, at least in my environment. We cloned this project and passed the test.

lib/plugin.js

  onRequest(fn) {
    this.interceptors.request.use(async config => await fn(config) || config)
  },
  onResponse(fn) {
    this.interceptors.response.use(async response => await fn(response) || response)
  },

Please update as a bug(?) fix if possible,
Thank you in advance.

Copy link
Member

farnabaz commented Mar 15, 2021

It should work without any changes, because both module and axios itself supports Promises

https://github.com/nuxt-community/axios-module/blob/main/types/index.d.ts#L20-L21
https://github.com/axios/axios/blob/master/index.d.ts#L125-L128

Do you mind creating a reproduction sample using template.nuxtjs.org

@insell824
Copy link
Author

insell824 commented Mar 15, 2021

Thank you for the response.

I'm getting an error when using async when extending onRequest in plugins.

This is the sample. Contains errors ver.
https://codesandbox.io/s/funny-meadow-zwo93?file=/plugins/axios-extension.js

This sample is trying to get the README.me in the static directory.

~/plugins/axios-extension.js

export default ({ $axios }) => {
  $axios.onRequest(async () => {
    console.log("onRequest()");
  });
};

~/pages/index.vue

// at methods
async clicked() {
  try {
    this.messages.push("Clicked");
    const { data } = await this.$axios.get("/README.md");
    this.messages.push("Finish. " + data);
  } catch (err) {
    this.messages.push("Error occurred. " + err.message);
    console.error(err);
  }
}

NOT ASYNC (Success) onRequest(()=>{})
image

ASYNC (Failed) onRequest(async ()=>{})
image

@jonasjancarik
Copy link

jonasjancarik commented Apr 8, 2021

I came across the same error message when using an async function in onRequest. I think the problem might be that async functions by default return a promise (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#return_value) but here you need to return the config object to pass it further to Axios.

Try something like this:

$axios.onRequest(async function (config) {
    try {
            await [SOMETHING]
            console.log('Awaited function finished')
        } catch (error) {
            console.log(error)
        }
    return config
  })

It took me a while to realise because the docs say "these functions don't have to return anything by default" (https://axios.nuxtjs.org/helpers) but I guess the implicitly returned promise overrides the config object which would otherwise be passed on in the background by default.

@insell824
Copy link
Author

Thank you for your reply.

The code as instructed worked fine.

Just in case, I shared the sample code that I forked and modified.
https://codesandbox.io/s/priceless-cartwright-5sgj7?file=/plugins/axios-extension.js

Thank you so much!

@areindl
Copy link

areindl commented Nov 12, 2021

I came across the same error message when using an async function in onRequest. I think the problem might be that async functions by default return a promise (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#return_value) but here you need to return the config object to pass it further to Axios.

Try something like this:

$axios.onRequest(async function (config) {
    try {
            await [SOMETHING]
            console.log('Awaited function finished')
        } catch (error) {
            console.log(error)
        }
    return config
  })

It took me a while to realise because the docs say "these functions don't have to return anything by default" (https://axios.nuxtjs.org/helpers) but I guess the implicitly returned promise overrides the config object which would otherwise be passed on in the background by default.

You Sir, are a legend! That should definitely be in the docs.

@areindl areindl linked a pull request Nov 12, 2021 that will close this issue
@areindl
Copy link

areindl commented Nov 12, 2021

I created a PR (#548) to resolve this gap in the docs

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

Successfully merging a pull request may close this issue.

4 participants