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

Vuex中Fetch GET请求传双参数返回异常,单参数正常

问题排查与解决:Fetch传递双参数返回400错误

问题现象

调用航班价格API时,同时传递origin和destination两个动态参数返回400 Bad Request,但固定其中一个参数、仅动态传递另一个时能正常获取数据。

不生效代码

async getFlights(context, { selectedPoint, departurePoint }) {
    
  const res = await fetch(
    `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=${selectedPoint}&destination=${departurePoint}&show_to_affiliates&token=${context.state.token}`,
  );
  if (res.ok) {
    let result = await res.json();
    context.commit('setFlights', result.data);
  }
  return res.ok;
},

生效代码示例

仅动态传origin

async getFlights(context, selectedPoint) {
    
  const res = await fetch(
    `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=${selectedPoint}&destination=LED&show_to_affiliates&token=${context.state.token}`,
  );
  if (res.ok) {
    let result = await res.json();
    context.commit('setFlights', result.data);
  }
  return res.ok;
},

仅动态传destination

async getFlights(context, departurePoint) {
    
  const res = await fetch(
    `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=LED&destination=${departurePoint}&show_to_affiliates&token=${context.state.token}`,
  );
  if (res.ok) {
    let result = await res.json();
    context.commit('setFlights', result.data);
  }
  return res.ok;
},

排查与解决步骤

  1. 检查参数合法性

    • 确认selectedPoint和departurePoint是否为有效的3位大写IATA机场代码,是否存在空值、小写字母或其他无效格式。
    • 调用API前添加参数校验:
      if (!selectedPoint || !departurePoint || selectedPoint.length !== 3 || departurePoint.length !== 3) {
        console.error('无效的机场代码参数');
        return false;
      }
      
  2. URL参数编码
    手动拼接URL时,参数值若包含特殊字符会破坏URL格式,需用encodeURIComponent编码:

    const encodedOrigin = encodeURIComponent(selectedPoint);
    const encodedDest = encodeURIComponent(departurePoint);
    const res = await fetch(
      `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=${encodedOrigin}&destination=${encodedDest}&show_to_affiliates&token=${context.state.token}`,
    );
    
  3. 查看API错误详情
    400错误时,打印返回的错误信息可明确API拒绝请求的具体原因:

    if (!res.ok) {
      const errorMsg = await res.text();
      console.error('API请求错误:', errorMsg);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:12:58