前言
javascript端的使用也比较方便,
首先 安装 express express-graphql graphql
npm install express express-graphql graphql --save
下面让我们修改我们的“hello world”示例,以便它是一个API服务器
/** * Created by TF016591 on 2017/11/2. */ var express = require('express'); var graphqlHTTP = require('express-graphql'); var {buildSchema} = require('graphql'); // Construct a schema, using GraphQL schema language var schema = buildSchema(` type Query { hello: String }`); // The root provides a resolver function for each API endpoint var root = { hello: function () { return 'Hello world!'; } }; var app = express(); app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, })); app.listen(4000); console.log('Running a GraphQL API server at localhost:4000/graphql');
运行:
node app.js
访问:
直接访问:localhost:4000/graphql?query={hello}
或者游览器访问 http://localhost:4000/graphql 地址
返回:
{
"data": {
"hello": "Hello world!"
}
}