GraphQL一个简单的入门示例

34次阅读

共计 1514 个字符,预计需要花费 4 分钟才能阅读完成。

GraphQL 一个简单的入门示例

准备

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>

运行结果

正文完
 0