You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Axios GET请求中设置可选参数similarText并规避Lint警告

实现Axios GET请求中similarText参数的可选性

要让similarText成为可选参数,同时避免Lint警告,可以用以下两种实用方法:

方法一:给函数参数设置默认值

直接给value参数设置默认值(比如undefined),既满足参数可选的需求,又符合Lint对可选参数的规范要求:

export const getProducts = async (
  value: string | undefined = undefined,
  apiKey: string | undefined
) => {
  const products = await axios
    .get(`${VITE_BACKEND_URI}/products?param1=match_token&param2=match_token`, {
       params: {
         // 仅当value存在时,才传入similarText参数
         ...(value && { similarText: value }),
       },
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json', // 这里建议修正为正确的Content-Type值,比如application/json
      },
    })
    .then((response) => response.data)
    .catch((error) => error)
  return products
}

这里用对象展开运算符...做了判断:只有value存在时,才会把similarText加入params对象。如果value是undefined,params里就不会包含这个键,后端也就不会接收到该参数,完美实现可选效果。

方法二:动态构建params对象

如果不想修改函数参数定义,可以在构建params时做判断,动态决定是否添加similarText,同时还能优化固定参数的写法:

export const getProducts = async (
  value: string | undefined,
  apiKey: string | undefined
) => {
  const params: Record<string, string> = {
    param1: 'match_token',
    param2: 'match_token'
  }
  // 存在value时才添加可选参数
  if (value) {
    params.similarText = value
  }

  const products = await axios
    .get(`${VITE_BACKEND_URI}/products`, {
       params,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    })
    .then((response) => response.data)
    .catch((error) => error)
  return products
}

这种方式把固定参数和可选参数分开处理,逻辑更清晰,还避免了在URL里拼接固定参数的冗余写法。

另外提一句:你代码里的Content-Type设置有误,应该写具体的类型值(比如application/json),而不是'Content-Type',建议修正这个小问题。

内容的提问来源于stack exchange,提问作者Dereemii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:45:56