Home > Enterprise >  how pass a var in the axios?
how pass a var in the axios?

Time:03-17

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'.

CodePudding user response:

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

CodePudding user response:

URL parameters aren't supported, and it seems they have no intention on adding it, given they expect you to use template strings. Here there's a discussion: https://github.com/axios/axios/issues/706

Axios GET method takes two arguments: the first being the URL string, and the second argument, we have it configure object with the property called params.

Axios Code:

axios.get("http://localhost/example"){
       params{
          name: myName
          example: 2
}}

Express Code:

app.get("example", (req, res){
const name : request.query.name
const example: request.query.example
}
  • Related