客戶端訪問Graphql 接口

一、在下面代碼中添加如下代碼,然后創(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: ['張飛', '曹操', '關(guān)羽']
        }
        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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容