微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决带有 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 举报,一经查实,本站将立刻删除。