Home > Back-end >  How can I send data on a get and receive a return?
How can I send data on a get and receive a return?

Time:12-03

I have to send this data in a get request but I don't know how to do it. Can you help me?

const ROUTE = "public/v1/route";

export async function showRoute(
  flow: string,
  token: string
): Promise<RouteParams> {
  const response = await client.get(ROUTE);
  return response.data;
}

CodePudding user response:

You can use async/await or .then() promise chaining:

import {showRoute} from './path-to-showRoute'

showRoute(/* params */).then(data => sendGetRequest(data))

//or

async function sendRouteInfo(){
  const routeData = await showRoute(/* params */)
  if (routeData) sendGetRequest(routeData)
}

PS: sendGetRequest is a mock function which simply sends a get request using axios or fetch

CodePudding user response:

axios.get(${URL}) .then(response => console.log(response.data) .catch(err)=> console.log(err)


That is when you are using axios (npm i axios) then import it

CodePudding user response:

I think what you're looking for is the Fetch-API. For example,

const ROUTE = resourcePath   '?'   new URLSearchParams({ ...params })

fetch(ROUTE) // sends a GET request
  .then((res: Response) => res.json() as MyExpectedDataType) // parses JSON response content
  .then((data: MyExpectedDataType) => {
    // do something with data
  })
  .catch(err => {
  })

// or
async function showRoute(): Promise<Something> {
  try {
    const res: Response = await fetch(ROUTE)
    const data = await res.json() as MyExpectedDataType
    // do something with data
  }
  catch (err) {
  }
}

fetch returns a Promise type on which you can chain asynchronous callbacks using .then and handle errors with .catch and .finally. You can also pass request method, headers, body content etc. as an optional second argument to fetch, see the documentation.

  • Related