捕获除 /graphql 之外的所有路由

Catch all routing except for /graphql

我有一个 node.js 服务器应用程序,它使用 express 和 apollo-server-express 来为我的应用程序提供服务。我想使用包罗万象的路由方法为我的 React 客户端提供服务,但是,我仍然想公开 /graphql 端点。我该怎么做才能使 /graphql 不被我的其余路由卡住?谢谢

import express from 'express';

const app = express();

app.get('/graphql', (request, response) => {
  // ? not sure what to do here.l
});

app.get('*', (request, response) => {
  response.sendFile('index.html', { root: '.' });
});

如果您确实在使用 apollo-server-express 包,则不必手动定义 /graphql 路由,如果您想将 Apollo 与 express 中间件结合使用,建议使用该包。 official documentation 实际上让您走上了正确的轨道。在您的特定情况下,您的服务器设置应如下所示:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.get('*', (request, response) => {
  console.log('catch-all hit.');
});

app.listen({ port: 3000 }, () =>
  console.log(` Server ready at http://localhost:3000${server.graphqlPath}`)
);

只需确保在执行 server.applyMiddleware 之后定义 catch-all 路由,这会为您设置 /graphql 端点。这样 /graphql 端点首先被命中并将用于处理这些请求。所有其他请求将由 catch-all.

处理