-
依赖
- 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了。
-
测试
接下来在左边的命令窗口中输入
{hello}
然后点击播放按钮就可以看到服务器返回的结果了
使用graphql创建API服务器
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...