Troubleshooting axios GET request in JavaScript: despite successfully pushing data to an array, encountering errors when using promise

I'm attempting to send a GET request to a free API in order to retrieve an array of all French departments. Initially, I encountered an issue where I was getting an empty result, which I later figured out was due to not waiting for the GET request to finish. I then implemented promise.all to ensure it waits, but even then, I'm still encountering errors and receiving undefined results. Here's the code snippet:

Create an array of departments:

const axios = require('axios')

let postalCode_all = []

for(let i = 1; i < 97; i++) {

    if(i < 10){
        postalCode_all.push("0" + i)
    } else {
        postalCode_all.push(i)
    }
}

Set up the GET request to the API:

let departements = [];

async function use_api(dep)  {

        try {
            const response = await axios.get("https://geo.api.gouv.fr/departements/" + dep + "?fields=region");
            departements.push(response);

        } catch (err) {
            console.error(err);
        }
    };

Send the GET request for all the elements in the previously created array:

(async () => {
    const result = await Promise.all(
        postalCode_all.map(element => {
            return use_api(element);
        })
    )
    console.log(result)
})()

Edit: The errors (404) might be due to departments like number 20 not existing, so it seems like the actual issue stems from an array of undefined elements. I'll need to look into this further.

Answer №1

After testing your code, I encountered a few issues, but I was able to make it work. The main problem lies here:

const response = await axios.get("https://api.example.com/data/" + id + "?fields=info");
data.push(response);

It seems that you are pushing the entire HTTP response object into the array instead of just the data you need. To rectify this, you should modify it like so:

data.push(response.data);

Furthermore, in the function fetch_data(), you are simply adding data to the data array without utilizing it further. Instead of

console.log(result)

you should use

console.log(data)

and work with that array accordingly.

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

Handling a JSON array error when working with a JSON string field

Attempting to create a JSONArray object with nested arrays and json strings, specifically looking at the "res" field. [{ "time": 123813213, "value": [{ "name": "task", "res": "{\"taskName\" : \"NAME\", \"ta ...

React app experiencing freezing due to custom asynchronous function utilisation

I am currently facing an issue with my personal project where the application freezes under certain circumstances. The initial load works fine, but when I make changes to the code causing React to re-render, the app just freezes. It seems to be related to ...

What is the best way to split two sets of radio buttons with the same name into distinct blocks in an HTML form?

For my project, I am working with two sets of radio buttons where the values are stored in a Database. Depending on another result in the HTML form, I need to display one set of radio buttons or the other. The issue arises when using the same name for all ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

Looking for assistance with retrieving all files from a directory based on their file extensions in JavaScript

Looking for a way to gather all the '.txt' files from a folder that also contains a 'backup' folder, and moving them into the 'backup' folder using Node.js. If you have any suggestions, please share. Thanks! Best regards, M ...

Update the value after verifying the element

I am trying to retrieve data from my database and update the values when an element is clicked (accepting user posts). The code I have written seems to work, but I encounter an error stating that props.actions is not a function when clicking on an element. ...

Using both ng-if and ng-click in AngularJS for enhanced functionalities

There's a button that should display a toggle only when the value is greater than 0; otherwise, it shouldn't do anything. This snippet of code shows how things were prior to adding ng-if: <span >{{values.valuesNumber}} <i class= ...

Adding a line break in a Buefy tooltip

I am trying to show a tooltip with multiple lines of text, but using \r\n or is not working. <b-tooltip label="Item 1 \r\n Item 2 \r\n Item 3" size="is-small" type="is-light" position="is-top" animated multilined> ...

Thirteen consecutive attempts to fetch information have resulted in failure

I've encountered an issue while attempting to fetch data from my .NET Core 7 API. The error message I'm receiving is as follows: *Unhandled Runtime Error Error: fetch failed Call Stack Object.fetch node:internal/deps/undici/undici (11413:11) pro ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

The jQuery .on("change") function keeps triggering repeatedly, but I'd like it to only execute once

I'm currently working on a feature that involves detecting changes to input text fields. Every time the user makes a change in an input field, I need to capture the new value and validate it. However, I've noticed that the code I have implemented ...

Unexpected unhandled_exception_processor in Google Chrome

I keep encountering a strange uncaught exception handler in Google Chrome. After updating all follow buttons to download JavaScript asynchronously, I noticed an error in the content.js file mentioned in the exception message which advises against polluting ...

Sending an HTTP request from a React application to an API hosted on the local server

My primary PC is running a react app on http://localhost:3000, along with a nodejs and express API on http://localhost:3001. The react app successfully requests data from the API on the same machine. However, when I try to access the react app from a dif ...

Struggling to Parse JSON Arrays in Node.js

Embarking on a journey with Node JS and Express, I find myself facing the challenge of developing a small proof of concept API in Node. The main hurdle I'm currently encountering stems from my limited understanding of how to parse JSON arrays to extr ...

The POST request made using Postman shows an empty Node.js/Express req.body

Here is the current code snippet I am working with: var express = require('express'); var router = express.Router(); var db = require('../helpers/db'); var data = { "1": 127, "2": 236, "3": 348 } router.get('/', ...

Generate a commitment from the function

I know the basics of JavaScript Promise and promise chain, but I'm looking to deepen my understanding. For example, take a look at the method provided below. It's in TypeScript, but can be adjusted for JavaScript ES6. private InsertPersonInDB(p ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Autocomplete fails to recognize any modifications made to the original object

I am currently utilizing the jQuery library's autocomplete() method on a text input field, setting Object.getOwnPropertyNames(projects) as the source: $(function() { $("#project").autocomplete({source: Object.getOwnPropertyNames(projects)}); } B ...

What is the purpose of using a hash in a WebSocket handshake?

When establishing a Websocket connection, the client initiates by connecting to a tcp socket on a server and then performs a handshake. In the client's handshake, there is a base64 encoded key (Sec-WebScoket-Key). The expected response from the serv ...