[SOLVED] how pass a var in the axios?

Issue

I’m trying to pass a var to the axios more by what I’m seeing it just accepts string is there any way to pass a var ?

My code:

router.get('/albuns', async (req, res)=>{
  const response = await axios.get(req.query.id)

  return console.log(response)
})

Error:

Argument of type ‘string | ParsedQs | string[] | ParsedQs[] | undefined’ is not assignable to parameter of type ‘string’.

Type ‘undefined’ is not assignable to type ‘string’.

Solution

This is just a Typescript warning because axios.get() expects a string argument but the default req.query can provide various types.

You just need to cast the value

const response = await axios.get(req.query.id as string);

Another option is to type the request in your handler signature

import { Request } from "express";

interface AlbunsQuery {
  id: string;
}

type AlbunsRequest = Request<{}, any, any, AlbunsQuery>;

router.get("/albuns", async (req: AlbunsRequest, res) => {
  const response = await axios.get(req.query.id);

  // etc
});

Answered By – Phil

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *