官方文档定义:一种用于API的查询语言, Graph + Query 有如下特色javascript
先后端联调接口一直以来都是特别费劲的一个环节,使用REST接口,接口返回的数据格式,数据类型(有哪些字段,字段的类型)都是后端本身预先定义好的,若是返回的数据格式并非调用者所指望的,做为前端的咱们能够经过如下两种方式去解决html
其实咱们真的很但愿, 咱们须要什么数据,须要什么格式,后端就按照什么格式给咱们返回什么样的数据结构,咱们要哪些字段,后端就只给咱们返回咱们须要的这些字段, 其余的都不返回,这样,前端就和后端解耦了,咱们不用再天天和后端由于接口问题去撕逼,GraphQL就是一个这样的思路来帮助咱们解决这个先后端联调接口的问题, 在前端直接写查询, 后端只管给前端返回前端查询的这些数据;前端
一个页面里展现的信息, info1, info2, info3,前端须要请求多个接口,info1对应的接口A中的a字段,info2对应的接口B中的b字段,info3对应的接口C中的c字段java
// /api/user/A
{
id: 1111,
name: '张三',
a: '当前页面要展现的info1',
b: 'b'
// 其余字段
}
// /api/order/B
{
id: 2222,
name: 'hahah',
a: 'a'
b: '当前页面要展现的info2',
// 其余字段
}
// /api/system/C
{
id: 3333,
name: 'hehe',
a: 'a'
c: '当前页面要展现的info3',
// 其余字段
}
复制代码
这个时候,稍微有点脾气的前端,都会去找后端撕逼,node
前端A: “就这三个字段,你还让我请求三个接口,你不能一个接口都返回给我吗”, 后端B:“哎, 我也想啊,可是xxxxx, 因此我这边很差改,”, ... 最后那就这样吧。ios
固然,我举得这个例子是一个很简单的场景,实际开发过程当中要比这个还要复杂;git
若是使用GraphQL的话,前端本身写查询,这个页面须要哪些需哪数据,后端就返回给哪些数据, 这是考虑到后端全部的接口都在同一个域下面,可是通常比较复杂的系统,后端都会分为不一样的域, 用户域,商品域,基础模块域,交易域等等,这时即便用了GraphQL也可能github
后端C:“你看其余都不是我负责的域,我要是本身给你封装一个,我本身底层须要通过xxxxx等复杂的步骤去获取其余域的,这个很复杂, 你仍是直接去他哪一个域去查询吧”,web
有两种方法,express
npm i --save express express-graphql graphql cors
复制代码
var express = require('express');
var graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');
const cors = require('cors'); // 用来解决跨域问题
// 建立 schema,须要注意到:
// 1. 感叹号 ! 表明 not-null
// 2. rollDice 接受参数
const schema = buildSchema(` type Query { username: String age: Int! } `)
const root = {
username: () => {
return '李华'
},
age: () => {
return Math.ceil(Math.random() * 100)
},
}
const app = express();
app.use(cors());
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
app.listen(3300);
console.log('Running a GraphQL API server at http://localhost:3300/graphql')
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>graphql demo</title>
</head>
<body>
<button class="test">获取当前用户数据</button>
<p class="username"></p>
<p class="age"></p>
</body>
<script> var test = document.querySelector('.test'); test.onclick = function () { var username = document.querySelector('.username'); var age = document.querySelector('.age'); fetch('http://localhost:3300/graphql', { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, method: 'POST', body: JSON.stringify({ query: `{ username, age, }` }), mode: 'cors' // no-cors, cors, *same-origin }) .then(function (response) { return response.json(); }) .then(function (res) { console.log('返回结果', res); username.innerHTML = `姓名:${res.data.username}`; age.innerHTML = `年龄:${res.data.age}` }) .catch(err => { console.error('错误', err); }); } </script>
</html>
复制代码