andriansandi
andriansandi

Reputation: 89

How to perform Async/Await in NodeJS

I have created a module / function in NodeJS to perform axios using async function in NodeJS.

The code like this:

const axios = require('axios');
const im = axios.create({
    baseURL: process.env.IM_API_URL,
    auth: {
        username: process.env.IM_API_KEY
    },
    headers: {
        'Content-Type': 'application/json'
    }
});

const {
    VirtualAccount
} = require('../models');

module.exports = {
    createVA: async function (userId, name, bank_code="ANZ") {
        try {
            const res = await im.post("/callback_virtual_accounts", {
                            external_id: "VA_fixed_" + userId,
                            bank_code: bank_code,
                            name: name
                        });
            const user = await VirtualAccount.findOne({ where: { userId: userId }});
            if(user === null) {
                const VA = VirtualAccount.create(
                    {
                        bankCode: res.data.bank_code,
                        accountNumber: res.data.account_number,
                        merchantCode: res.data.merchant_code,
                        externalId: res.data.external_id,
                        refId: res.data.id,
                        userId: userId
                    }
                )

                return VA;
            }
            return res.data;
        } catch(error) {
            console.log(error);
            return error;
        }
    }
}

This code will be called inside express controller:

step_5: async (req, res) => {
   try {
      const user = await User.findOne({
        where: { id: req.user.id },
        raw: true
      });

      const VA = await im.createVA(user.id, user.name);
      res.status(200).send(VA);
   } catch (error) {
      res.status(500).send(error); 
   }
};

Can this controller be called inside ReactJS application using axios also, but chrome always state error message: net::ERR_CONNECTION_REFUSED

PS: Sorry for the dumb questions, i'm a php developer which is code to nodejs rite now.

Upvotes: 0

Views: 101

Answers (1)

Elan Hamburger
Elan Hamburger

Reputation: 2177

ERR_CONNECTION_REFUSED means that the server you're attempting to contact is refusing to connect with your computer. Usually this is because you've made a typo in the URL and you're attempting to contact a server that doesn't exist or the server process isn't running so there's nothing listening at the requested port.

Double check that your IM_API_URL environment variable is set correctly. If it is not set, set to a server that is not running, or set to an invalid hostname, you'll get this error.

Upvotes: 1

Related Questions