首页 > 解决方案 > 在gql(Apollo客户端)中传入变量时出现400错误请求

问题描述

我正在尝试将一些变量传递到我的 gql 字符串中,但似乎无法使其正常工作。手动传递数据时,查询有效。

  const UPDATE_WEATHER = gql`
  {
    weatherByLocation(
      latitude: "51.8917473"
      longitude: "-2.0877334999999997"
    ) {
      currently {
        summary
      }
    }
  }
`;

const WeatherInfo = ({ lat, long }) => {
  const { loading, error, data } = useQuery(UPDATE_WEATHER, {
    variables: { lat, long },
  });

  if (loading) return null;
  if (error) return `Error! ${error}`;

  return <h1>{data.weatherByLocation[0].currently.summary}</h1>;
};

我尝试按照此处的指南进行操作,但没有成功。这是我用变量更新的 gql

const UPDATE_WEATHER = gql`
  query weatherByLocation($lat: String!, $long: String!) {
    weatherByLocation(latitude: $lat, longitude: $long) {
      currently {
        summary
      }
    }
  }
`;

但是,这会导致 400 错误请求。这是请求有效负载

operationName: "weatherByLocation"
query: "query weatherByLocation($lat: String!, $long: String!) {↵  weatherByLocation(latitude: $lat, longitude: $long) {↵    currently {↵      summary↵      __typename↵    }↵    __typename↵  }↵}↵&quot;
variables: {lat: 51.891751299999996, long: -2.0877779}

标签: reactjsgraphqlapollo-client

解决方案


您需要将变量转换为字符串!因为在查询中,您期望具有字符串类型的变量


推荐阅读