【GraphQL学习】01-Express初搭建GraphQL接口

系统需要安装nodejs环境,版本最好是12.22.0或者14.16.0或者大于等于16.0.0,我用的是14.16.0版本的(这里用nvm管理node版本会比较方便)
在这里插入图片描述

  1. 首先初始化项目 npm init -y,会生成package.json文件
    (这个.gitignore是我自己在项目初始化之前就配置的git配置文件,一般自己练习的项目有没有都无所谓)
    在这里插入图片描述
  2. 安装express和graphql以及express-graphqlnpm install express graphql express-graphql -S
    在这里插入图片描述
  3. 为了方便热更新代码,可以安装nodemonnpm i nodemon -g,这个必须全局安装
    在这里插入图片描述
  4. 新建启动文件index.js,并且写一个基础的demo,启动nodemon index.js启动项目,看到打印出来了http://localhost:3000/graphql就成功了
    在这里插入图片描述
    附上代码
// 引入 express 核心库
const express = require('express');
// 引入 结合 express 和 graphql 的中间件
const { graphqlHTTP } = require('express-graphql');
// 引入 graphql 核心库
const { buildSchema } = require('graphql');
// buildSchema 定义查询语句和类型, Query:语句,hello:查询方法名称,String:返回值类型
const schema = buildSchema(`
  type Query {
    hello: String,
  }
`);
// root 查询处理器,hello:查询方法 及 返回值
const root = {
  hello: () => {
    return 'hello graphql test';
  },
};
const app = express();
// /graphql:接口,graphqlHTTP:graphql处理中间件
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  // 是否启用调试界面,false不能调试
  graphiql: true,
}));
// 监听3000端口
app.listen(3000, () => { console.log('http://localhost:3000/graphql')} );
  1. 浏览器打开http://localhost:3000/graphql
    在这里插入图片描述
  2. 点击右上角Docs,可以查看root types,删掉左边所有,输入
query {
	hello
}

点击运行,可以得到结果hello graphql test
在这里插入图片描述

  1. 基础的项目搭建就完成了,接下来再继续学习graphql的其他语法和用法吧

PS:我测试了下其他类型和自定义类型的数据,需要什么数据取什么数据,不会所有数据都返回,附上代码,看图说话:

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
  type User {
    username: String
    age: Int
    sex: String
    address: String
  }
  type Query {
    hello: String
    height: Int
    accountInfo: User
  }
`);
const root = {
  hello: () => {
    return 'hello graphql test';
  },
  height: () => {
    return 288
  },
  accountInfo: () => {
    return {
      username: 'hsieh chia',
      age: 22,
      sex: 'girl',
      address: 'sichuan, chengdu'
    }
  }
};
const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(3000, () => { console.log('http://localhost:3000/graphql')} );

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值