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-graphql
2.启动项目测试
命令: node server.js
遇上端口占用问题,停掉或者改用其他端口。
相关命令:
lsof -i :4000
kill -9 端口号(上图为,47806)
如上所示,启动成功。
访问地址: localhost:4000/graphql
访问成功
3.定义复杂类型
定义一个 学生类型 student
const 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’));
运行结果
发表回复