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

首次用Next.js14+GraphQL+Apollo+Stepzen做天气项目遇405错误求助

排查Next.js 14 + Apollo + Stepzen天气项目的405/Bad Request错误

错误信息

⨯ node_modules/@apollo/client/errors/index.js (28:27) @ call
ApolloError: Connector: HTTP Error: Bad Request
    at new Promise (<anonymous>)
    at Array.forEach (<anonymous>)
null
 ⨯ node_modules/@apollo/client/errors/index.js (28:27) @ call
 ⨯ ApolloError: Response not successful: Received status code 405
    at new Promise (<anonymous>)
    at Array.forEach (<anonymous>)
digest: "1155966032"

问题排查与修复步骤

1. 修正变量名不匹配问题

你的GraphQL查询定义的变量是$past_days,但在page.tsx的请求中传的是pastdays,参数名不一致会直接导致Bad Request错误:

  • 修改page.tsx中的variables部分,把pastdays: "false"改为past_days: "false":
const { data } = await client.query({
  query: fetchWeatherQuery,
  variables: {
    current: "true",
    daily: "true",
    hourly: "true",
    latitude: lat,
    longitude: long,
    timezone: "GMT",
    past_days: "false", // 修正变量名
  },
});

2. 修正经纬度参数类型

路由参数lat和long是字符串类型,但天气API(及Stepzen连接器)通常要求经纬度为数字类型,字符串会导致请求无效:

  • 在page.tsx中把lat和long转换为数字:
const { data } = await client.query({
  query: fetchWeatherQuery,
  variables: {
    current: "true",
    daily: "true",
    hourly: "true",
    latitude: Number(lat), // 转为数字类型
    longitude: Number(long), // 转为数字类型
    timezone: "GMT",
    past_days: "false",
  },
});

3. 验证Stepzen API配置

405错误通常是请求URL无效或方法不允许,需确认:

  • 确保process.env.API_URL是正确的Stepzen GraphQL endpoint,格式应为https://<你的Stepzen账户名>.stepzen.net/api/<你的endpoint名称>/__graphql
  • 检查.env文件中API_URL和STEPZEN_API_KEY配置是否正确,服务器组件无需给环境变量加NEXT_PUBLIC_前缀
  • 可在getClient中打印环境变量值,确认是否正确加载

4. 优化Apollo Client实例创建

当前getClient每次调用都会创建新实例,虽不直接引发错误,但会影响性能,建议缓存实例:

import { ApolloClient, InMemoryCache } from "@apollo/client";

let client: ApolloClient<any> | null = null;

export const getClient = () => {
  if (!client) {
    client = new ApolloClient({
      uri: process.env.API_URL,
      cache: new InMemoryCache(),
      headers: {
        Authorization: `apikey ${process.env.STEPZEN_API_KEY}`,
      },
    });
  }
  return client;
};

5. 检查Stepzen连接器配置

确认你的Stepzen schema文件(通常为.graphql或.sdl)中,连接器的参数映射与天气API要求一致,没有拼写或类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:11:00