It appears that the execution of the request in Alphavantage was unsuccessful

Upon running the code snippet below, I noticed that the terminal outputs "function called" and "end function", but skips over the intermediate console.log(). It seems like the request is not being executed properly. Any ideas why this might be happening?

export const retrieveData : Function = () => {
    console.log('function called');
    const url = `https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=${key}`;

    axios.get(url,{
        responseType: 'json',
        headers: { 'User-Agent': 'request' }
    })
    .then(response => {
        console.log('first step', response);
        // return response.json(); 
        return response; 
    })
    .then(data => {
        console.log('second step');
        console.log(data)
        return 'hola'
    } )
    .then(successMessage => {
        console.log('success',successMessage);
    })
    .catch(error => console.error(`Error: ${error}`));

    console.log('end function');

};

I've tested the same URL and key in Postman, and there were no issues with the endpoint. Everything worked perfectly.

Answer №1

When making a call using response = axios.get(url), the actual data can be found in response.data as opposed to just response. Refer to the parent schema for more detailed information, available here

{
  // `data` represents the response provided by the server
  data: {},

  // `status` indicates the HTTP status code of the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  // In HTTP/2, status text may be blank or unsupported.
  // (Refer to HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4)
  statusText: 'OK',

  // `headers` contains the HTTP headers sent by the server in response
  // All header names are lowercase and accessible via bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` encompasses the configuration provided to `axios` during the request
  config: {},

  // `request` refers to the associated request that resulted in this response
  // In node.js, it's the last ClientRequest instance (in redirects),
  // while in the browser, it's an XMLHttpRequest instance
  request: {}
}

Therefore, the desired format for returning data should be:

    axios.get(url,
        {
            responseType: 'json',
            headers: { 'User-Agent': 'request' }
        })
    .then(response => {
        return response.data; 
    })

Demo code

Save this as a file named get-data.ts.

const axios = require('axios');

export const retrieveData: Function = () => {
    const key = 'your API key'
    console.log('function called');
    const url = `https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&apikey=${key}`;

    axios.get(url,
        {
            responseType: 'json',
            headers: { 'User-Agent': 'request' }
        })
    .then(response => {
        return response.data; 
    })
    .then(data => {
        console.log(JSON.stringify(data, null, 4))
        return 'hello'
    })
    .then(successMessage => {
        console.log('success', successMessage);
    })
    .catch(error => console.error(`Error: ${error}`));
    console.log('end function');
}
retrieveData();

Transpile into JavaScript and run it

tsc get-data.ts
node get-data.js

Result

https://i.sstatic.net/H8odC.png

This method ensures JSON formatting with a 4-space indent for improved readability.

JSON.stringify(data, null, 4)

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

Exploring TypeAhead functionality in Reactjs 18

I have encountered an issue while using react-bootstrap-typeahead version 5.1.8. The problem arises when I try to utilize the typeahead feature, as it displays an error related to 'name'. Below is my code snippet: import { Typeahead } from " ...

Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet: enum Status { SUCCESS = 'success', FAILED = 'fa ...

Implementing the breadcrumb component within dynamically loaded modules loaded through the router-outlet component

I'm currently working on an angular 8 breadcrumb component for my application. The requirement is to display it in the content of the page, not just in the header, and it should never be located outside the router-outlet. This has posed a challenge fo ...

Utilizing a service within NestJS

I'm currently in the process of updating some older code and I have created a service that I want to inject into the constructor of a class. There are two key points to consider about this particular class. The first point is that it is instantiated b ...

Using promises in TypeScript index signature

Can you help me find the correct index signature for this particular class? class MyClass { [index: string]: Promise<void> | Promise<MyType>; // not working public async methodOne (): Promise<void> { ... } public async methodTwo () ...

Struggling to transfer data between a component and a template

I have set a variable called MIN_PW above the export class MyComponent. The intellisense recognizes it in my formBuilder, but it is not displaying properly in the UI (UI shows "Password must contain at least characters"). Initially, I had defined the vari ...

NGXS TypeError: Freezing not possible in Angular

https://i.sstatic.net/uD6Vp.png The block of code responsible for triggering the specified action constructor(auth: AuthService, private store: Store) { this.userAuth = auth.signedIn.subscribe({ next: (user) => { this.user = user; thi ...

Classification of Function Data

file1.tsx const handleData = (dataEvent: SimpleUiEvent) => { DataCollection.sendEvent(dataEvent); }; <File2 key={card.title} triggerData={() => handleData(card.dataEvent)} {...card} /> file2.tsx const handleCardFlip = () => ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

What is the best way to create an ESM / CJS module without needing to include '.default' in the imports?

Is it possible to configure my package.json to support different imports for CJS and ESM formats? "main": "dist/cjs/index.js", "module": "dist/esm/index.js", In addition, can I set up my TypeScript compiler to g ...

Ways to conditionally display a component in Next.js without the issue of caching CSS styles

I'm a newcomer to Next.js and I'm still trying to wrap my head around how the caching works. Let's take a look at this simplified example: An index page that displays either Test1 or Test2 components, based on whether the current minute is ...

Acquire information from the user interface and display it in a highcharts chart using Angular 5

Currently, I am utilizing an npm package for chart creation, which can be found at the following link: https://www.npmjs.com/package/angular-highcharts I have a specific interface set up and I aim to extract values from this interface to populate a line g ...

Angular 8: Setting up Variable Dependency within a Component Class

I have a dilemma in Angular where I need to work with two objects of the same type. public addressFinalData: AddressMailingData; mailingArchive: AddressMailingData[] = []; Is there a way to subscribe to data objects of the same type within one componen ...

Steps for creating a TypeScript project with React Native

Hey there, I'm just starting out with react-native and I want to work on a project using VS Code. I'm familiar with initializing a project using the command "react-native init ProjectName", but it seems to generate files with a .js extension inst ...

Transfer the task of loading data from a component to context in React using Typescript

I am working on a component/page/homepage where I have a type called Profil. The type is defined as follows: interface HomePageState { profile: Profil | undefined } const [state, setState] = useState<HomePageState>({ profile: undefined, }) ...

What could be causing input to be blocked in certain situations while using my Angular directive with compile function?

Recently, I created a directive that adds a class based on a certain condition. You can find the code snippet at the end of this question. The directive functions as expected in a simple use case where it's applied to a required field: <input typ ...

Error in Typescript: Attempting to access the property 'set' of an undefined value

Currently, I am in the process of setting up a basic example of push notifications on Android using Nativescript and Typescript. Although my code may seem a bit messy, I am struggling with properly rewriting "var Observable = require("data/observable");" a ...

Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component: <div class="form-group"> <label>{{l("RoomType")}}</label> <p-dropdown [disabled] = "!roomTypes.length" [options]= ...

Encountering an error while testing Jasmine + Angular with Typescript: "TypeError: 'undefined' is not an object."

I'm having some difficulty while trying to test a specific service. It seems that I am struggling to match the mock response correctly: public getCustomerDetails(customerID:string): ng.IPromise<ICustomerDetails> { return this.testService.g ...

Debug a Typescript-enabled Koa application remotely from a Docker container using Webstorm

Issue: Currently facing challenges while setting up a new NodeJS Project using KoaJS, Typescript, and Docker. The initial setup went as planned, but encountering some difficulties with remote debugging - or at least it seems so from my perspective. When s ...