GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时。GraphQL 并没有和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑。
这里我门以 Node.js 的 express 框架为例,看一下 Hello World 的 GraphQL 版本。
mkdir myapp
cd myapp
npm init (一路回车)
npm install express express-graphql graphql
创建一个应用的启动文件,比如 server.js,内容如下:
var express = require('express');
var { graphqlHTTP } = require('express-graphql');
var { buildSchema } = require('graphql');
var schema = buildSchema(`
type Query {
hello: String
}
`);
var root = { hello: () => 'Hello World!' };
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
这里几个主要变量说一下:
启动服务
node server.js
使用浏览器访问 http://localhost:4000/graphql,可以看到 GraphiQL IDE 的界面,输入
query {
hello
}
可以看到下面的查询结果
{
"data": {
"hello": "Hello world!"
}
}
或者也可以使用 curl 命令查询
curl -X POST http://localhost:4000/graphql -d 'query=query {
hello
}'
{"data":{"hello":"Hello world!"}}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有