Home > Blockchain >  How to consume Axios all from Node.js backend in ReactJS frontend?
How to consume Axios all from Node.js backend in ReactJS frontend?

Time:10-20

I have multiple get requests with axios.all in my Node.js backend. I want to return the response to the function and then consume this as API in ReactJS. When I use console.log to output the data in the React component, I get Promise { <state>: "pending" }, but I want to get data from the Node.js backend.

Could you please help me?

Node.js backend:

export async function getArrivalPorts() {

    let endpoints = [
        'https://api.github.com/users/ejirocodes',
        'https://api.github.com/users/ejirocodes/repos',
        'https://api.github.com/users/ejirocodes/followers',
        'https://api.github.com/users/ejirocodes/following'];

   const response = await axios.all(endpoints.map((endpoint) => axios.get(endpoint)))
       .then(axios.spread((
           {data: user},
           {data: repos},
           {data: followers},
           {data: following}) => {
           return ({user, repos, followers, following});
       }))
       .catch(errors => {
           console.log(errors)
       })
    return(response)

}


Node.js router

router.get('/arrival', getArrivalPorts)

ReactJS frontend

function From ()
{
    const data = axios.get('http://localhost:5000/arrival')
    console.log(data)
}

CodePudding user response:

Try once with by add await before "axios.get(". like :

await axios.get(

CodePudding user response:

use .then() method of Promise object

function From() {
    const data = axios.get('http://localhost:5000/arrival')
      .then(data => {
        console.log(data);
      });
}

reply to your comment

Your current problem looks like CORS rejection. you can just handle it by configuring proxy server if you used create-react-app to make your project.

official documentation to configure proxy in CRA

  1. Make sure that your frontend project is "create-react-app" based.
  2. open the package.json at the root directory of your frontend proejct.
  3. add this property to the package.json
"proxy": "http://localhost:5000",

If you have no idea where to put this code in the package.json, just put at the top of the "scripts" property, so that your package.json should look like this:

{
  "name": "blabla...",
  // ... some codes
  "dependencies": {
    // ...some packages
  },
  "proxy": "http://localhost:5000",
  "scripts": {
    "start": "react-scripts start",
    // ...some scripts
  },
  // blablabla
}
  1. start (or restart) the dev-server of your frontend project
  • Related