一、在下面代碼中添加如下代碼,然后創(chuàng)建一個public文件夾,在文件夾中建一個html文件,然后發(fā)送post請求獲取數(shù)據(jù)
例如:創(chuàng)建的是index.html,然后執(zhí)行js文件,然后訪問http://localhost:3000/index.html
// 公共文件夾,供用戶訪問靜態(tài)資源
app.use(express.static('public'))
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');
// 定義Schema, 查詢方法和返回值類型
const schema = buildSchema(`
// Account 為自定義類型
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 = {
11: ['張三', '李四', '王五'],
12: ['張飛', '曹操', '關羽']
}
return obj[classNo];
},
account({username}) {
const name = username;
const age = 12;
const sex = '男';
const department = '測試部';
const salary = ({city}) => {
if (city == '北京' || city == '上海' || city == '廣州') {
return 10000;
}
return 4000;
}
return {
name,
age,
sex,
department,
salary
}
}
}
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
// 公共文件夾,供用戶訪問靜態(tài)資源
app.use(express.static('public'))
app.listen(3000);
html文件.png