官方文档
https://graphql.org/
安装命令: npm install graphql --save
const { graphql, buildSchema} = require('graphql')
// 1. 使用Graphql schema 语法构建一个schema
const schema = buildSchema(`
type Query {
name: String
age: Int
}
`)
// 2. 定义schema 的 resolver
const rootValue = {
name() {
return 'tom'
},
age() {
return 20
}
}
// 3. 查询
graphql(schema, '{name, age}', rootValue).then(res => {
console.log(res)
})
[服务端] 运行Express GraphQL服务
安装命令: npm install express express-graphql graphql cors --save
新建 app.js
文件如下:
const {buildSchema} = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const cors = require('cors')
const app = express()
// 允许客户端进行跨域请求
app.use(cors())
// 1. 使用Graphql schema 语法构建一个schema
const schema = buildSchema(`
type Query {
name: String
age: Int
}
`)
// 2. 定义schema 的 resolver
const rootValue = {
name() {
return 'tom'
},
age() {
return 20
}
}
// 3. 挂载 Graphql 中间件
app.use('/graphql', graphqlHTTP({
schema,
rootValue,
graphiql: true // 开启浏览器 Graphql IDE 调试工具
}))
// 4. 启动web服务
app.listen(4000, () => {
console.log('Graphql Server is running at http://localhost:4000/graphql')
})
启动命令: node app.js
访问http://localhost:4000/graphql进行查询,效果如下:
[客户端] fetch数据
fetch("http://localhost:4000/graphql", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({query: "{ name }"})
})
.then(r => r.json())
.then(data => console.log('data returned:', data))