執行 GraphQL API 伺服器的最簡單方式是使用 Express,這是 Node.js 的熱門網頁應用程式架構。您需要安裝兩個額外的相依性
npm install express graphql-http graphql ruru --save
讓我們修改我們的「hello world」範例,使其成為 API 伺服器,而不是執行單一查詢的指令碼。我們可以使用「express」模組執行網頁伺服器,並使用 graphql-http
函式庫在「/graphql」HTTP 端點上掛載 GraphQL API 伺服器,而不是直接使用 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 languagevar schema = buildSchema(` type Query { hello: String }`)
// The root provides a resolver function for each API endpointvar 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 portapp.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 查詢。