带有 Apollo-Server 的 Next.JS 上的 API 路由:为什么使用 basePath 会导致错误?

问题描述

我在带有 Apollo-Server 的 Next.JS 应用程序上使用 API Routes,以围绕 REST 端点创建 GraphQL API 包装器。但如果项目有 bathPath,我就会遇到问题。

我一直在关注this examplevideo tutorial on youtube。 我使用该教程中的 repo 复制了我的问题。运行该代码 $ yarn dev 并导航到 http://localhost:3000/api/graphql 后,GraphQl 游乐场就会出现,并按预期工作。

但是,如果我向项目添加基本路径,则 graphQl 游乐场仍然可以正常显示在 http://localhost:300/basepath/api/graphql 上,但它给了我“无法访问服务器”的错误显示开发工具的网络选项卡中出现 404 错误

为了添加基本路径,我创建了一个 next.config.js添加

module.exports = {
   basePath: '/basepath'
}

pages/api/graphql.ts 中,我将路径从 /api/graphql 更新为 /basepath/api/graphql

import { ApolloServer } from "apollo-server-micro";
import { schema } from "src/schema";

const server = new ApolloServer({ schema });
const handler = server.createHandler({ path: "/somewhere/api/graphql" });

export const config = {
  api: {
    bodyParser: false,},};

export default handler;

src/apollo.ts 中,我将 HttpLink uri 从 /api/graphql 更新为 /basepath/api/graphql

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

let apolloClient: ApolloClient<normalizedCacheObject>;

function createIsomorphicLink() {
  if (typeof window === "undefined") {
    // server
    const { SchemaLink } = require("@apollo/client/link/schema");
    const { schema } = require("./schema");
    return new SchemaLink({ schema });
  } else {
    // client
    const { HttpLink } = require("@apollo/client/link/http");
    return new HttpLink({ uri: "/bathpath/api/graphql" });
  }
}

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === "undefined",link: createIsomorphicLink(),cache: new InMemoryCache(),});
}

export function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient();

  if (initialState) {
    _apolloClient.cache.restore(initialState);
  }

  if (typeof window === "undefined") return _apolloClient;
  apolloClient = apolloClient ?? _apolloClient;

  return apolloClient;
}

export function useApollo(initialState) {
  const store = useMemo(() => initializeApollo(initialState),[initialState]);
  return store;
}

任何想法为什么添加基本路径会破坏此设置?我需要做什么来修复它?

这是我第一次在堆栈溢出上发帖,所以我希望我的描述足够好,请询问我是否遗漏了什么,并提前感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)