Home > Mobile >  Getting data with axios and posting to localhost using express
Getting data with axios and posting to localhost using express

Time:03-20

I am new to javascript and am trying to fetch data from an API then post it to my own server (localhost).

I get the data using axios below:

async function getNCAA() {
    axios
    .get(`https://api.the-odds-api.com/v4/sports/${sportKey1}/scores/?daysFrom=1&apiKey=${apiKey}`)
    .then((res) => {
        console.log(res.data)
        console.log("Remaining requests", res.headers["x-requests-remaining"]);
        console.log("Used requests", res.headers["x-requests-used"]);
        return res.data
    })
    .catch((error) => {
        console.log("Error status", error.response.status);
        console.log(error.response.data);
        return error
    });
}

assign the data

let result = getNCAA();

then try to send it using express:

app.get('/', (req, res) => {
    res.send(result);
});

The result returns a Promise object that I don't know how to access.

I've been able to access this data in the past by using a useState but I am not running a React app in this particular case

CodePudding user response:

You have to learn about Promise/Asynchronus.

function getNCAA() {
    axios
    .get(`https://api.the-odds-api.com/v4/sports/${sportKey1}/scores/?daysFrom=1&apiKey=${apiKey}`)
    .then((res) => {
        console.log(res.data)
        console.log("Remaining requests", res.headers["x-requests-remaining"]);
        console.log("Used requests", res.headers["x-requests-used"]);
        return res.data
    })
    .catch((error) => {
        console.log("Error status", error.response.status);
        console.log(error.response.data);
        return error
    });
}
router.get('/', (req, res) => {
  getNCAA()
   .then(result => {
     res.send(result)
   })
   .catch((e) => {
    // error handler
   });
});

CodePudding user response:

Not sure if it's good practice but I just nested it all together and it works.

async function getNCAA() {
    axios
    .get(`https://api.the-odds-api.com/v4/sports/${sportKey1}/scores/?daysFrom=1&apiKey=${apiKey}`)
    .then((result) => {
        // console.log(res.data)
        console.log("Remaining requests", result.headers["x-requests-remaining"]);
        console.log("Used requests", result.headers["x-requests-used"]);

        app.get('/', (req, res) => {
            res.send(result.data);
        });
        })
    .catch((error) => {
        console.log("Error status", error);
    });

    return ;
}

getNCAA();
  • Related