官方文档

https://graphql.org/
安装命令: npm install graphql --save

  1. const { graphql, buildSchema} = require('graphql')
  2. // 1. 使用Graphql schema 语法构建一个schema
  3. const schema = buildSchema(`
  4. type Query {
  5. name: String
  6. age: Int
  7. }
  8. `)
  9. // 2. 定义schema 的 resolver
  10. const rootValue = {
  11. name() {
  12. return 'tom'
  13. },
  14. age() {
  15. return 20
  16. }
  17. }
  18. // 3. 查询
  19. graphql(schema, '{name, age}', rootValue).then(res => {
  20. console.log(res)
  21. })

[服务端] 运行Express GraphQL服务

安装命令: npm install express express-graphql graphql cors --save
新建 app.js 文件如下:

  1. const {buildSchema} = require('graphql')
  2. const express = require('express')
  3. const { graphqlHTTP } = require('express-graphql')
  4. const cors = require('cors')
  5. const app = express()
  6. // 允许客户端进行跨域请求
  7. app.use(cors())
  8. // 1. 使用Graphql schema 语法构建一个schema
  9. const schema = buildSchema(`
  10. type Query {
  11. name: String
  12. age: Int
  13. }
  14. `)
  15. // 2. 定义schema 的 resolver
  16. const rootValue = {
  17. name() {
  18. return 'tom'
  19. },
  20. age() {
  21. return 20
  22. }
  23. }
  24. // 3. 挂载 Graphql 中间件
  25. app.use('/graphql', graphqlHTTP({
  26. schema,
  27. rootValue,
  28. graphiql: true // 开启浏览器 Graphql IDE 调试工具
  29. }))
  30. // 4. 启动web服务
  31. app.listen(4000, () => {
  32. console.log('Graphql Server is running at http://localhost:4000/graphql')
  33. })

启动命令: node app.js
访问http://localhost:4000/graphql进行查询,效果如下:
image.png

[客户端] fetch数据

  1. fetch("http://localhost:4000/graphql", {
  2. method: 'POST',
  3. headers: {
  4. 'Content-Type': 'application/json',
  5. 'Accept': 'application/json',
  6. },
  7. body: JSON.stringify({query: "{ name }"})
  8. })
  9. .then(r => r.json())
  10. .then(data => console.log('data returned:', data))