apollo-server-koa 简单使用

server.js

import koa from 'koa'; // koa@2   npm install --save koa@2
import koaRouter from 'koa-router'; // koa-router@next
import koaBody from 'koa-bodyparser'; // koa-bodyparser@next
import { graphqlKoa, graphiqlKoa } from 'apollo-server-koa';
import schema from './src/graphql/schema.js';
import executableSchema from './src/graphql/executableSchema';

const app = new koa();
const router = new koaRouter();
const PORT = 3000;

// koaBody is needed just for POST.
router.post('/graphql', koaBody(), graphqlKoa({ schema: executableSchema }));
router.get('/graphql', graphqlKoa({ schema: executableSchema }));

router.get('/graphiql', graphiqlKoa({ endpointURL: '/graphql' }));

app.use(router.routes());
app.use(router.allowedMethods());
app.listen(PORT,()=>console.log(`localhost:${PORT}`));

package.json


{
  "name": "mcbeath",
  "version": "1.0.0",
  "description": "my mcbeath network",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "babel-node server.js"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "apollo-server-koa": "^1.1.2",
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.0",
    "graphql": "^0.11.5",
    "koa": "^2.3.0",
    "koa-bodyparser": "^3.2.0",
    "koa-router": "^7.1.1"
  }
}

必备文件说明
apollo-server-koa:apollo graphql服务
babel-cli:是一个工具,可以帮助你在JavaScript的最新版本编写代码。当你的环境支持不支持某些功能本身,Babel会帮助你编译的功能到一个支持的版本。
babel-preset-env:babel的环境变量,可以支持你的浏览器
graphql: The GraphQL specification is edited in the markdown files found in  /spec  the latest release of which is published at http://facebook.github.io/graphql/ .
koa中间件使用异步函数表达es2017
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.
koa-bodyparser:A body parser for koa, base on co-body. support json, form and text type body.
koa-router:Router middleware for koa

.babelrc配置 (必不可少否则最新语法无法编译)

{
  "presets": [
    ["env", {
      "targets": {
        "node": true
      }
    }]
  ]
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值