如何在 axios 中传递 var?

how pass a var in the axios?

我正在尝试将 var 传递给 axios,我看到它只接受字符串,有什么方法可以传递 var 吗?

我的代码:

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

  return console.log(response)
})

错误:

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

Type 'undefined' is not assignable to type 'string'.

这只是一个 Typescript 警告,因为 axios.get() 需要一个 string 参数,但默认 req.query 可以提供各种类型。

你只需要转换值

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

另一种选择是在您的处理程序签名中输入请求

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

URL 参数不受支持,他们似乎无意添加它,因为他们希望您使用模板字符串。 这里有一个讨论:https://github.com/axios/axios/issues/706

Axios GET 方法有两个参数:第一个是 URL 字符串,第二个参数是我们用 属性 调用的参数配置对象。

Axios 代码:

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

快递编码:

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