【问题标题】:Catch all routing except for /graphql捕获除 /graphql 之外的所有路由
【发布时间】:2020-12-29 06:50:32
【问题描述】:

我有一个 node.js 服务器应用程序,它使用 express 和 apollo-server-express 来为我的应用程序提供服务。我想使用包罗万象的路由方法为我的反应客户端提供服务,但是,我仍然想公开/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: '.' });
});

【问题讨论】:

    标签: node.js express graphql apollo-server


    【解决方案1】:

    如果您确实在使用 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 之后定义了你的包罗万象的路由,它会为你设置/graphql 端点。这样/graphql 端点首先被命中并将用于处理这些请求。所有其他请求将由 catch-all 处理。

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 2017-01-12
      • 2021-08-13
      相关资源
      最近更新 更多