GraphQL(4):GraphQL clients访问接口

下面演示在GraphQL clients访问GraphQL 接口

1 修改baseType.js

添加可供用户访问的静态资源路径

代码如下:

复制代码
const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;
// 定义schema,查询和类型
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: ['张三', '李四', '王五'],
            61: ['张大三', '李大四', '王大五']
        }
        return obj[classNo];
    },
    account({ username}) {
        const name = username;
        const sex = 'man';
        const age = 18;
        const department = '开发部';
        const salary = ({city}) => {
            if(city === "北京" || city == "上海" || city == "广州" || city == "深圳") {
                return 10000;
            }
            return 3000;
        }
        return {
            name,
            sex,
            age,
            department,
            salary
        }
    }
}

const app = express();

app.use('/graphql', grapqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

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

app.listen(3000);

2 编写index.html页面

设置参数

设置传入的数值

完整代码如下:

复制代码
<!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>Document</title>
</head>
<body>
    <button onclick="getData()">获取数据</button>
</body>
<script>
    function getData() {
        const query = `
        query Account($username: String, $city: String) {
            account(username: $username) {
                name
                age
                sex
                salary(city: $city)
            }
        }
        `

        const variables = {username: '李大四', city: '深圳'}

        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>

启动服务:

复制代码
node baseType.js

访问地址后,点击获取数据按钮,效果如下:

相关推荐
神奇小汤圆22 分钟前
Codex 子 Agent 配置指南:让 Sol 当军师,Luna 当搬砖工
后端
ClouGence24 分钟前
2026 年 4 款数据库管理工具推荐:免费、开源、付费怎么选?
数据库·后端·开源
大勇前进1 小时前
React 中 State 为什么不能直接修改?很多新手一直没懂
后端
大黄评测1 小时前
useState 与 useReducer 该怎么选?别只会无脑用 useState
后端
乐橙开放平台1 小时前
物业 SaaS 笔记:子账号 Policy 按通道隔离,At_ 管控面 / St_ 数据面治理 accessToken
后端·物联网·音视频
站大爷IP1 小时前
Python的is和==把我坑惨了,原来对象比较的水这么深
后端
fatcoder1 小时前
玩转Nginx 04 — 反向代理:给 nginx 接上后端
前端·后端·nginx
雨落倾城夏未凉1 小时前
halcon核心-颜色识别/颜色控件转换(十)
后端
SomeB1oody1 小时前
【RustyML入门】5.2. 分类指标
开发语言·后端·机器学习·rust·教程
明月_清风3 小时前
Pi Agent 深度解析:开源极简终端 AI 编码代理的终极指南
前端·后端·ai编程