运行 GraphQL API 服务器的最简单方法是使用 Express,这是一种流行的 Node.js Web 应用框架。你将需要安装两个额外的依赖:
¥The simplest way to run a GraphQL API server is to use Express, a popular web application framework for Node.js. You will need to install two additional dependencies:
npm install express graphql-http graphql --save
让我们修改“hello world”示例,使其成为 API 服务器而不是运行单个查询的脚本。我们可以使用 ‘express’ 模块来运行 Web 服务器,而不是直接使用 graphql
函数执行查询,我们可以使用 graphql-http
库在“/graphql”HTTP 端点上挂载 GraphQL API 服务器:
¥Let’s modify our “hello world” example so that it’s an API server rather than a script that runs a single query. We can use the ‘express’ module to run a webserver, and instead of executing a query directly with the graphql
function, we can use the graphql-http
library to mount a GraphQL API server on the “/graphql” HTTP endpoint:
var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
// 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,
})
)
// Start the server at port
app.listen(4000)
console.log("Running a GraphQL API server at http://localhost:4000/graphql")
你可以使用以下命令运行此 GraphQL 服务器:
¥You can run this GraphQL server with:
node server.js
使用 GraphiQL
¥Using GraphiQL
GraphiQL 是 GraphQL 的 IDE;查询和探索 GraphQL API 的好方法。将其添加到你的服务器的一种简单方法是通过 MIT 许可的 ruru 包,该包将预构建的 GraphiQL 与一些流行的增强功能打包在一起。为此,请使用 npm install --save ruru
安装 ruru
模块,然后将以下内容添加到你的 server.js
文件中,然后重新启动 node server.js
命令:
¥GraphiQL is GraphQL’s IDE; a great way of querying and exploring your GraphQL API.
One easy way to add it to your server is via the MIT-licensed ruru package which bundles a prebuilt GraphiQL with some popular enhancements.
To do so, install the ruru
module with npm install --save ruru
and then add the following to your server.js
file, then restart the node server.js
command:
var { ruruHTML } = require("ruru/server")
// Serve the GraphiQL IDE.
app.get("/", (_req, res) => {
res.type("html")
res.end(ruruHTML({ endpoint: "/graphql" }))
})
如果你导航到 http://localhost:4000,你应该会看到一个允许你输入查询的界面;现在你可以使用 GraphiQL IDE 工具直接在浏览器中发出 GraphQL 查询。
¥If you navigate to http://localhost:4000, you should see an interface that lets you enter queries; now you can use the GraphiQL IDE tool to issue GraphQL queries directly in the browser.
至此,你已经学习了如何运行 GraphQL 服务器。下一步是学习如何 从客户端代码发出 GraphQL 查询。
¥At this point you have learned how to run a GraphQL server. The next step is to learn how to issue GraphQL queries from client code.