1

I want to make MSA so i want to use front server and backend server both. So frontend calls api/route structure file api. and File api calls backend api with axios. the problem is return new Response(callAxios()) code keeps telling me red line error mark probably can not confirm type like JSON or String. No problem with using cuz still i can get JSON data but how can i remove the red line error mark I am not familiar with typescript and just started today.

enter image description here

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
  })
}

Remove the error mark and make sure accepting data type is correct.

1 Answer 1

1

I'd be aiming for something more like this:

import axios from "axios"

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

async function callAxios(){
  const result = await axios.get('http://localhost:8080/firstCall', {
    params: { // query string
      title: 'NEXT JS'
    },
    headers: { 
      'X-Api-Key': 'my-api-key'
    },
  });

  console.log(result, result.data);
  return result.data;
}

You either use async and await or you use callbacks, not both.

14
  • 1
    when using async and await you surround it with try and catch as it'll throw on promise rejection Mar 17 at 8:16
  • 1
    JSON.parse(jsonData) as JSON is a built in object that provides the function parse Mar 17 at 8:19
  • 1
    If you are having to use JSON.stringify then it means axios has already parsed the json for you. I may be wrong. Mar 17 at 8:26
  • 1
    If you type this into your browser url, what do you get? http://localhost:8080/firstCall?title=NEXT%20JS, or http://localhost:3000/api/hello Mar 17 at 8:32
  • 1
    I'd need to see more code to help debug. We have fixed your initial problem. I suggest you create another question describing your current problem in more detail. Mar 17 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.