GraphQL - GraphQL Clients

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

视频 5

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 onclick="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

尽管会报错,可忽略。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值