GraphQL - GraphQL Clients
程序员文章站
2022-03-09 22:50:51
...
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 ο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
尽管会报错,可忽略。
上一篇: Android对话框
下一篇: android对话框
推荐阅读
-
在vue项目中集成graphql(vue-ApolloClient)
-
Graphql入门
-
ASP.NET Core使用GraphQL第二章之中间件
-
ASP.NET Core使用GraphQL第一章之Hello World
-
前端从零开始学习Graphql
-
【视频】使用ASP.NET Core开发GraphQL服务
-
一个类GraphQL的ORM数据访问框架发布
-
使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下)
-
在vue项目中集成graphql(vue-ApolloClient)
-
spark2+kafka报错:java.lang.NoSuchMethodError:org.apache.kafka.clients.consumer.KafkaConsumer.subscribe