GraphQL 学习一、什么是GraphQL一种用于 API 的查询语言二、学习GraphQL开始撸码学习1.写一个 server.js 文件const express = require(’express’);const graphqlHTTP = require(’express-graphql’);const {buildSchema} = require(‘graphql’);const schema = buildSchema( type Query { hello: String });const root = {hello: () => ‘Hello world!’};const app = express();app.use(’/graphql’, graphqlHTTP({ schema: schema, rootValue: root, graphiql: true,}));app.listen(4000, () => console.log(‘Now browse to localhost:4000/graphql’));使用命令1. 使用 npm init -y 初始化一个 package.json 文件2. 安装所需插件 npm install express express-graphql graphql -S遇上错误如上:项目名称不能使用 grapql,修改成 my-graphql2.启动项目测试命令: node server.js遇上端口占用问题,停掉或者改用其他端口。相关命令: lsof -i :4000 kill -9 端口号(上图为,47806) 如上所示,启动成功。访问地址: localhost:4000/graphql访问成功3.定义复杂类型定义一个 学生类型 studentconst express = require(’express’);const graphqlHTTP = require(’express-graphql’);const {buildSchema} = require(‘graphql’);const schema = buildSchema( type Student{ name:String age:Int } type Query { hello: String name:String student:Student });const root = { hello: () => ‘Hello world!’, name:()=>{ return ‘zhangbf’ }, student:()=>{ return { name:‘张三丰’, age:18 } }};const app = express();app.use(’/graphql’, graphqlHTTP({ schema: schema, rootValue: root, graphiql: true,}));app.listen(4000, () => console.log(‘Now browse to localhost:4000/graphql’));运行结果