当前位置: 首页 > news >正文

GraphQL(2):使用express和GraphQL编写helloworld

1 安装express、graphql以及express-graphql

在项目的目录下运行一下命令。

npm init -y

npm install express graphql express-graphql -S

2 新建helloworld.js

代码如下:

const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;
// 定义schema,查询和类型
const schema = buildSchema(`type Query {hello: String}
`)
// 定义查询对应的处理器
const root ={hello:()=>{return 'hello world';}
}
const app = express();
app.use('/graphql', grapqlHTTP({schema: schema,rootValue: root,graphiql: true
}))
app.listen(3000);

启动程序

node helloworld.js

访问服务

地址如下:http://localhost:3000/graphql

点击Docs后,发现里面有只有一个query接口

测试接口,返回结果如下

3 修改代码为多个参数

const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;
// 定义schema,查询和类型
const schema = buildSchema(`type Account {name: Stringage: Intsex: Stringdepartment: String}type Query {hello: StringaccountName: Stringage: Intaccount: Account}
`)
// 定义查询对应的处理器
const root ={hello: () => {return 'hello world';},accountName: () => {return '张三丰';},age:()=>{return 18;},account: ()=>{return {name: '李四光',age: 18,sex: '男',department: '科学院'}}
}
const app = express();
app.use('/graphql', grapqlHTTP({schema: schema,rootValue: root,graphiql: true
}))
app.listen(3000);

启动后发现端口参数如下

结果如下:

http://www.lryc.cn/news/360727.html

相关文章:

  • Vue中的计算属性和侦听器:提升响应式编程的艺术
  • JavaScript倍速播放视频
  • ER图介绍
  • Oracle通过datax迁移线上表到历史库
  • java基础-深拷贝和浅拷贝
  • Java数组操作
  • C++vector及其实现
  • 路由策略实验1
  • 含情脉脉的进程
  • 重复文件怎么查找并清理?电脑重复文件清理工具分享:4个
  • Java中连接Mongodb进行操作
  • LabVIEW远程开发与调试
  • C/C++|基于回调函数实现异步操作
  • Mac上搭建Python环境:深入探索与高效实践
  • 数据标准的制定落地
  • 微信小程序基础 -- 小程序UI组件(5)
  • Linux shell编程学习笔记55:hostname命令——获取或设置主机名,显示IP地址和DNS、NIS
  • 【鸟哥】Linux笔记-硬件搭配
  • 代码随想三刷数组篇
  • windows环境下重建oracle监听
  • 单元测试框架Pytest的基本操作
  • Java web应用性能分析之【java进程问题分析工具】
  • 02-2.3.2_2 单链表的查找
  • 设计模式(十四)行为型模式---访问者模式(visitor)
  • 【Matplotlib作图-3.Ranking】50 Matplotlib Visualizations, Python实现,源码可复现
  • 加入不正确的位置编码会破坏掉原本的信息吗?
  • 区块链合约开发流程
  • 建筑企业有闲置资质怎么办?
  • Java开发-特殊文本文件,日志技术
  • Django ORM深度游:探索多对一、一对一与多对多数据关系的奥秘与实践