使用 Express 和 GraphQL 而不是简单地使用 Node.js 和 GraphtQL 有什么好处?

What is the benefit of using Express with GraphQL instead of simply using Node.js with GraphtQL?

将 Express 与 GraphQL 结合使用有什么好处? GraphQL 的所有优点也可以在没有 Express 的简单 Node.js 应用程序中使用。由于 GraphQL 只有一个端点并且没有像 Express 那样的中间件概念,为什么我们要使用 Express 而不仅仅是 Node.js?

  1. Express 使用了 Node.js http 模块 under the hood but through middleware provides a way for you to implement various features for your endpoint. For example, to process POST requests (which you would need to do for GraphQL), you would need to parse the request body into a usable format -- if you don't utilize Express and a middleware like body-parser, you'd have to do this by hand. The same goes for other common functionality 你可能需要的,比如 CORS,session 管理等等 --既然有中间件,为什么还要重新发明轮子?

  2. GraphQL 本身可能没有中间件的概念(尽管 一个有效地 does just that 的库),Express 的中间件仍然适用于您的GraphQL 端点作为一个整体。这意味着您可以在 GraphQL 端点 运行 之前设置中间件。除了上面已经描述的功能之外,这还为您提供了为端点实施授权逻辑的机会。例如,您可以阻止未能提供适当自定义 header.

  3. 的用户访问整个端点
  4. 实际上,您的应用可能需要的不仅仅是 GraphQL 端点。身份验证通常在 GraphQL 之外通过公开一个或多个附加端点来处理——如果您为应用程序实现 OAuth flow,则尤其如此。同样,您可以与使用 webhook 的 third-party 服务交互,这将要求您专门为此目的在服务器上公开其他端点。这同样适用于健康检查,例如负载均衡器使用的健康检查。