Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost).

For fetching the data, I am using axios as shown 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
    });
}

Next, I need to store the fetched data.

let result = getNCAA();

Then, I attempt to send the data using express:

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

The issue arises when the result returns a Promise object that I struggle to access.

In previous cases, I could access this data by using useState, but in this instance, it's not a React app.

Answer №1

I tried a different approach by nesting everything together and surprisingly, it worked flawlessly.

async function retrieveNCAAInfo() {
    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 ;
}

retrieveNCAAInfo();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Show or hide side menu depending on when a div reaches the top of the

I have a side menu that opens when a specific div reaches the top of the window. The menu includes a toggle button for opening and closing it. However, I am encountering an issue where the script keeps closing the menu on scroll even after manually openi ...

Tumblr jQuery Like (utilizing rel attribute for selection)

I developed a custom HTML5 theme using masonry and infinite-scroll, which has been functioning well. I am now trying to add reblog and like buttons to each post but I'm facing an issue with the like button not working. Here is the URL to the theme: ...

Exploring ways to modify the default Keep Alive behavior in Express JS

While stress testing a nodejs express server, I discovered that it automatically includes a "Connection: Keep-Alive" header. However, my application only needs to expose a web api to the client and does not require the connection to remain open after recei ...

What is the correct way to add a library to webpack configuration?

Currently, I am working with Rails 6 and webpack in my project. I am interested in integrating the library jquery-textcomplete, but I am unsure about how to properly include it in the application.js file. Here are the steps I have taken so far: I instal ...

undefined reference to $

I'm currently working on a JavaScript project that involves using key events to display alphabets on the screen. However, I've encountered an error and need some assistance. <!DOCTYPE html> <html lang="en"> <head> <met ...

Guide to retrieving and showing specific items from a DropDownList in a Text box using JavaScript, HTML, and AngularJS

Can someone explain how to extract and select items from a DropDownList and display them in a Textbox using JavaScript/HTML/AngularJS? Here are more details: I have a dropdown list with many items. When I click on an item from the list, it should be dis ...

Surprising discovery of the reserved term 'await'

function retrieveUsers() { setTimeout(() => { displayLoadingMessage(); const response = fetch("https://reqres.in/api/users?page=1"); let userData = (await response.json()).data; storeAllUserDa ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

Troubleshooting a ForwardRef issue in a TypeScript and React Native project

Encountering a ts error while using forwardRef. // [ts] Property 'forwardRef' does not exist on type 'typeof React'. const MyComponent = React.forwardRef((props: Props, ref: any) => ... An issue arises in React Native when the pare ...

The process of extracting a value from an array of objects encountered an error due to the undefined object

I am looking to extract the value from an array within an object while also implementing error checking. The code I currently have checks if a specific key exists in the object and if the value associated with that key is of type array. If both condition ...

Custom label slots in q-file for the Quasar file picker for personalized file selection label

Can you provide guidance on how to properly display custom label slots in Quasar? I am looking to incorporate icons or images using the label slot. Below is my data(): data() { return { showLabel: true, labelText: "My custom Label& ...

Need to double tap to remove item in redux-toolkit

Trying to delete an item in Redux Toolkit, but having trouble as the remove function only works on screen. I have to press twice to delete the previous one. Here is the reducer: const noteReducer = createSlice({ name: "note", initialState: N ...

Utilizing Vue-chartjs and axios to create a dynamic stacked bar chart

Within my template, I include: <BarChart v-if="loaded" :data1="data1" :data2="data2" :chart-labels="labels" /> For the script section, I have: this.loaded = false axios.get(`url`).then((response) => ...

Can Next.js 13 support the usage of axios?

Despite trying to implement the SSG operation with the fetch option {cache: 'force-cache'}, I consistently received the same data even when the mock server's data changed. I found that using the fetch option {cache: 'no-store'} do ...

Modify the input based on the chosen option operation

I am working on a project where I have 3 select elements and when a user selects an option, the associated value should be displayed in an input field. I am trying to use a single function for these 3 selects, but I am facing some issues. Here is the HTML ...

next.js experiencing hydration issue due to using div tag instead of main tag

I've come across an issue with hydration in NextJS and after debugging, I discovered that using the div tag instead of the main tag is causing this problem. The error message I'm receiving Here is the code snippet that triggered the error impo ...

Having issues transferring the variable from JavaScript to PHP?

When attempting to pass a variable via AJAX request in JavaScript, I am encountering an issue where the variable is not being received in my PHP file. I'm unsure of where the problem lies. Can anyone help? JavaScript code var build = { m_count : ...

Should an exception be thrown or information returned when updating a document fails in Node.js?

I am currently working on a system with a updateDocument method in the service layer of a node.js, express, and mongoose application. I have a dilemma regarding the best practice for handling scenarios where the update operation fails, such as when an inco ...

PHP file secured to only accept variables posted from HTML form

This is a basic HTML/AJAX/PHP script I have implemented. <form id="new_user" action="" method="post"> <div class="col-md-3 form-group"> <label for="username">Username</label> <input type="text" class="form-control" name ...