In the api route.ts file, a JSON Response type is returned using axios

Creating an MSA involves utilizing both a front server and backend server. In this case, the frontend calls the api/route structure file api, which then calls the backend api using axios. However, I keep encountering a red line error mark when trying to use return new Response(callAxios()), most likely due to the inability to confirm the type as JSON or String.

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

import axios from "axios"

export async function GET(request: Request) {
  return new Response(callAxios())
}

async function callAxios(){
  await axios.get('http://localhost:8080/firstCall', {
    params: { // query string
      title: 'NEXT JS'
    },
    headers: { 
      'X-Api-Key': 'my-api-key'
    },
  }).then(res => {
      console.log(res.data)
      return res.data
  })
}

I am still able to retrieve JSON data despite the error mark, but how can I eliminate it? Note that I am new to TypeScript and have just started learning today.

Can you help me resolve the error mark and ensure the correct acceptance of data types?

Answer №1

This is the revised code snippet that I propose:

import fetch from "isomorphic-fetch"

export async function fetchData(request: Request) {
  return new Response(await handleFetch())
}

async function handleFetch(){
  const response = await fetch('http://localhost:5000/dataFetch', {
    method: 'GET',
    headers: { 
      'Authorization': 'Bearer my-access-token'
    },
  });

  console.log(response, response.json());
  return response.json();
}

The best practice is to either utilize async and await or stick with callbacks, not mix both approaches.

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

Trouble with loading TypeScript Express REST API routes!

I've been working on accessing data from my custom REST API, but I'm encountering an issue where the JSON data is not being displayed when I navigate to the endpoints. I have set up server, controller, and data controller classes in order to crea ...

How to eliminate Image notifications in NextJS

I keep receiving a warning about the local images on my website: Image with src "http://localhost:3000/_next/static/media/icon_home.0f967506.svg" has either width or height modified, but not the other. If you use CSS to change the size of your image, also ...

Is it feasible to select which modules to be loaded into the application?

Looking for a solution to my problem outlined in the title. For example, I am tasked with creating two separate versions of an app - one for France and one for the UK. In some areas, they require completely different implementations. Is it feasible to sw ...

Styling components in React using Styled Components is versatile and can

Insight Embarking on the creation of a React UI Library. Engaging with TS: 5.x, React: 18.x, Styled-Component: 5.x versions. Challenge Encountered Following deployment of the UI Library to the npm registry, executing yarn add my-custom-ui-library in a t ...

Is there a way for me to retrieve the text generated by OpenAI in the completion response?

let gptResponse = await openai .createCompletion({ model: "davinci", prompt, max_tokens: 60, temperature: 0.9, presence_penalty: 0, frequency_penalty: 0.5, best_of: 1, n: 1, stre ...

Encountering issues with utilizing Eeflector within a custom interceptor in NestJS. Module import error preventing functionality

I've been working on developing an interceptor for my NestJs application. My goal is to include some metadata in my controller method and then retrieve this data in my interceptor. So, I created my interceptor along with a custom decorator to add the ...

A beginner's guide to integrating components in Aframe with Nextjs

Hey there, I'm currently working on building a VR scene using Aframe and I want to add a custom Aframe component with click events just like in the example. Here's what I attempted: import type { NextPage } from 'next'; import React, { ...

Leveraging Angular Firebase MatTable with the power of 2 observables in 1

I'm currently facing an issue with my Firebase database data structure where I have a reference to a user id. Here's an example of the original data in my collection: { city: new york, country: usa addedBy: feibf78UYV3e43 // This is the USER ID ...

Troubleshooting: Issue with Button Layout in Ionic's ItemSliding Component

How can I create a list item that allows swiping to reveal an archive button? The requirement is for the icon to appear to the left of the text. I'm referring to the documentation on Button Layout: https://ionicframework.com/docs/api/components/item ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...

The SeekTo function in react-player is not working as expected

I've been encountering some difficulties while using the seekTo function with react-player in my next.js site. Whenever I attempt to use it, an error pops up saying: "playerRef.seekTo is not a function." I also tried using "playerRef.current.seekTo(p ...

Searching for a specific document using AngularFirestore - what's the best method?

Is it possible to create an Observable that is limited to a single document? While the code provided creates an Observable for querying multiple documents: foo.component.ts import { AngularFirestore } from '@angular/fire/firestore'; import { O ...

Is it beneficial to use TypeScript for writing unit tests?

We are in the process of transitioning from JavaScript to TypeScript within my team. One question that has come up is whether we should also migrate our unit tests from JavaScript to TypeScript. Personally, I am not convinced of the significant benefits o ...

Is there a way to include values in the body of an HTTP GET request using Angular?

I've created a function in my service that looks like this: /** * Retrieve all data * @param sendSelectedValues string */ getAllActPlanBalanceYearData(sendSelectedValues: any): Observable<any> { const url = `/yearlyvalues/act-and ...

What is the process for ensuring that the "ng-multiselect-dropdown" is a mandatory field within Angular 7?

Is there a way to require the ng-multiselect-dropdown field to have at least one selected item? <ng-multiselect-dropdown [placeholder]="'Select countries'" [data]="countries" [(ngModel)]="countriesSelectedItems" [settings]="co ...

What is the best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

(Angular) Best methods to search for a specific string in an array

Looking to retrieve a string value from an HTML input inside an array in Angular 5 using a service file within a component. My code login.component.ts export class LoginComponent implements OnInit { userData = []; constructor(private router: Route ...

Experiencing difficulty accessing the response header in Angular 16 due to CORS restrictions

When attempting to retrieve the response header from my post call, I am encountering difficulties as it appears there are "no headers" or I may be doing something incorrectly. On the backend, I am utilizing ASP.NET Core. Below is a basic outline of my API ...

Error: Couldn't locate Next.js - TypeScript module

I encountered an error with the image, but I am unsure of the reason behind it. Additionally, the directory is included in the second image. https://i.sstatic.net/knUzH.png import Link from 'next/link'; import { useState } from 'react' ...

Save user's email and password for future logins after the initial login

Is there a way to automatically populate the user's email and password in the login form when they check the "remember me" option and return to log in again? This is for a project using React and Next.js. ...