GraphQL一個簡單的入門示例

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>

運行結果

graphql

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章