-
依赖
- express
- express-graphql
- graphql
-
创建服务器
先要用express搭建服务器
const express = require('express') const http = require('http') const R = require('ramda') const PORT = process.env.PORT ? process.env.PORT : 22333 let app = express() app.get('/', (req, res) => { res.send('hello') }) const httpServer = http.createServer(app) httpServer.listen(PORT, () => { console.log(`http://localhost:${PORT}/`) })
要注意这里不要使用express的listen,方便以后对接https。
-
Schema
新建schema.js的文件:
const { buildSchema } = require('graphql') module.exports = buildSchema(` type Query{ hello:String } `)
-
Resolver
新建resolver.js
module.exports = { hello: ()=>'hello' }
-
在express中加入graphql中间件
const express = require('express') const http = require('http') const R = require('ramda') const gqResolver = require('./graphql/resolver') const gqSchema = require('./graphql/schema') const PORT = process.env.PORT?process.env.PORT:22333 let app = express() app.use('/graphql', expressGraphQL({ schema: gqlSchema, rootValue: resolver, graphiql: true })) app.get('/', (req, res) => { res.send('hello') }) const httpServer = http.createServer(app) httpServer.listen(PORT, () => { console.log(`http://localhost:${PORT}/`) })
如果一切顺利的话启动服务器之后打开localhost:PORT/graphql , 听过会出现如下的画面,这时打开右上角的docs,就可以查询之前创建的API了。
graphql.png -
测试
接下来在左边的命令窗口中输入
{hello}
然后点击播放按钮就可以看到服务器返回的结果了
graphql2.png
使用graphql创建API服务器
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。