欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GraphQL - GraphQL Clients

程序员文章站 2022-03-09 22:50:51
...

2019GraphQL入门到精通  https://www.bilibili.com/video/BV1Ab411H7Yv?from=search&seid=16813706797539177189

视频 5

GraphQL Clients

GraphQL - GraphQL Clients

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button οnclick="getData()">获取数据</button>
</body>
<script>
    function getData() {
        const query = `
        query Account($username: String) {
            account(username: $username) {
                name
                age
                sex
                salary(city:"北京")
            }
        }
        `
        const variables = {username: 'Jim'}


        fetch('/graphql', {
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify ({
                query: query,
                variables: variables
            })
        }).then(res => res.json)
        .then(json => {
            console.log(data);
        })
    }
</script>
</html>
const express = require('express');
const graphqlHTTP = require('express-graphql');
const {buildSchema} = require('graphql');


const schema = buildSchema (`
    type Account {
        name: String
        age: Int
        sex: String
        department: String
        salary(city: String): Int
    }
    type Query {
        getClassMates(classNo: Int!): [String]
        account(username: String): Account
    }
`)
const root = {
    getClassMates({classNo}) {
        const obj = {
            31: ['Jim', 'Jack', 'Jhon'],
            61: ['Kate', 'Kimi', 'Kevin']
        }
        return obj[classNo];
    },
    account({username}) {
        const name = username;
        const sex = 'm';
        const age = 18;
        const department = 'IT';
        const salary = ({city}) => {
            if (city == "北京" || city == "上海") {
                return 10000;
            }
            return 3000;
        }
        return { // 无序排列
            name,
            sex,
            age,
            department,
            salary
        }
    }


}
const app = express();
app.use('/graphql', graphqlHTTP({
    schema:schema,
    rootValue: root,
    graphiql: true //打开调试模式(开发者模式)
}))


// 公开文件夹,供用户访问静态资源
app.use(express.static('public'))


app.listen(3000);

1. node baseType.js

2. 浏览器输入 locahost:3000/index.html

GraphQL - GraphQL Clients

尽管会报错,可忽略。

GraphQL - GraphQL Clients

相关标签: GraphQL

上一篇: Android对话框

下一篇: android对话框