一、新建入口页面
在主目录下建立public/index.html文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Documenttitle> 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: 'four', city: 'chongqing'}
fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ query, variables: variables, }) }) .then(res => res.json()) .then(data => console.log(data)); } script> html>
|
二、配置静态文件
1
| app.use(express.static('public'))
|
三、graphql.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| const express = require('express'); const {buildSchema} = require('graphql'); const graphqlHTTP = require('express-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: ['h', 'l', 'c'], 61: ['m', 'n', 'j'] } return obj[classNo]; }, account({ username }) { const name = username; const sex = 'female'; const age = 18; const department = 'school'; const salary = ({city}) => { if(city == "beijing" || city == "shanghai" || city == "guangzhou" || city == "shenzhen") { 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);
|
四、使用
node启动本文件后,在本地页面内的网络请求中可以看到相关数据。