GraphQL LogoGraphQL

运行 Express GraphQL 服务器

运行 GraphQL API 服务器最简单的方法是使用 Express,这是一个流行的 Node.js Web 应用程序框架。您需要安装两个额外的依赖项

npm install express graphql-http graphql ruru --save

让我们修改我们的“hello world”示例,使其成为一个 API 服务器,而不是运行单个查询的脚本。我们可以使用“express”模块来运行 Web 服务器,并且可以使用 graphql-http 库将 GraphQL API 服务器安装在“/graphql”HTTP 端点上,而不是直接使用 graphql 函数执行查询

var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
var { ruruHTML } = require("ruru/server")
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`)
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return "Hello world!"
},
}
var app = express()
// Create and use the GraphQL handler.
app.all(
"/graphql",
createHandler({
schema: schema,
rootValue: root,
})
)
// Serve the GraphiQL IDE.
app.get("/", (_req, res) => {
res.type("html")
res.end(ruruHTML({ endpoint: "/graphql" }))
})
// Start the server at port
app.listen(4000)
console.log("Running a GraphQL API server at http://localhost:4000/graphql")

您可以使用以下命令运行此 GraphQL 服务器:

node server.js

您可以使用 Graph_i_QL IDE 工具直接在浏览器中发出 GraphQL 查询。如果您导航到 http://localhost:4000,您应该会看到一个界面,允许您输入查询。

此时,您已经了解了如何运行 GraphQL 服务器。下一步是学习如何 从客户端代码发出 GraphQL 查询

继续阅读 →GraphQL 客户端