Home > Software design >  How to use Axios inside an express router
How to use Axios inside an express router

Time:03-15

I have a React front-end that make an axios request to the back-end.

While in the back-end, under some circumstances, I need to make another axios request.

But the axios.patch doesn't run: it seems to executes the line, but after that it not execute the .then nor the .error lines.

I have a breakpoint set into the router.patch('/stripeUser', (req, res, next) => {} function, but it is not triggered.

If I try to call the same call use Postman, it succeeds.

Here is the back-end code:

router.post('/', async (req, res, next) => {

    const params = {
        user: req.body.data[0].user,
    }

    const customer = params.user.stripeId !== undefined
        ? await stripe.customers.retrieve(params.user.stripeId)
        : await stripe.customers.create({
            email: params.user.email
        });

    if (params.user.stripeId === undefined && customer.id !== undefined) {
        axios.patch('https://xxx.domain.com/users/update', { data: [{ userId: params.user.userId, stripeId: customer.id }] })
            .then((usr) => {
                console.log("User updated: stripeId: "   usr.user.stripeId)
                newCustomer = usr.user;
            })
            .catch(error => {
                console.log(error);
            });
    }

    const intermediate = usr.user.someTransform();

    res(intermediate) ???
    return intermediate ???

A secondary question:

If the axios.fetch should run, how could I pass its results usr to the rest of the program?

CodePudding user response:

Have you tried using await instead of then, since the function may return before axios has resolved the request response you may not be able to use the data you get in the promise callback in the same function if you don't wait the resolution.

const usr = await axios.patch('https://xxx.domain.com/users/update', 
    { data: [{ userId: params.user.userId, stripeId: customer.id }] })
    .catch(error => console.log(error));
const newCustomer = usr.user;
// ...

CodePudding user response:

Closing quote missing in the axios patch call.

axios.patch('https://xxx.domain.com/users/update', { data: [{ userId: params.user.userId, stripeId: customer.id }] })
                .then((usr) => {
                    console.log("User updated: stripeId: "   usr.user.stripeId)
                    newCustomer = usr.user;
                })
                .catch(error => {
                    console.log(error);
                });
  • Related