首先下载express,express-graphql和graphql
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
var schema = buildSchema(`
type Account{
name:String
}
type Query {
hello: String
account:Account,
getClass(classNo:Int!):[String]
},
`);
var root = { hello: () => 'Hello world!' ,
account:()=>{return {name:'xx'}},
getClass:({classNo})=>{
const obj={1:['xx','yy']}
return obj[classNo]
}
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'));
客户端请求数据
<button class="btn">点击</button>
<script>
var btn=document.getElementsByClassName('btn')[0];
var Account=`query GetClass($classNo:Int!){getClass(classNo:$classNo)}`
var variables={classNo:1}
btn.onclick=function(){
fetch('/graphql',{method:'post',headers:{'Content-Type':'application/json',
'Accept':'application/json'},body:JSON.stringify({query:Account,variables})}).then(data=>data.json()).then(data=>{console.log(data)})
}
</script>
<button class="btn">点击</button>
<script>
var btn=document.getElementsByClassName('btn')[0];
btn.onclick=function(){
var Account=`query {account{name},hello}`
fetch('/graphql',{method:'post',headers:{'Content-Type':'application/json',
'Accept':'application/json'},body:JSON.stringify({query:Account})}).then(data=>data.json())
.then(data=>{console.log(data)})
}
</script>