项目场景:
学习使用express-graphql
问题描述
node执行时报错
TypeError: graphqlHTTP is not a function
at Object.<anonymous> (F:\feiq\H52203STEP3\react\server\01-helloworld.js:14:21)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
原因分析
例如:express-graphql 的引用方式错误
解决方案:
改变引用方式
// const { graphqlHTTP } = require('express-graphql');
// 请注意,它使用的解构等效于:
// const graphqlHTTP = require('express-graphql').graphqlHTTP;
最终代码,hello-world
var express = require('express');
var {graphqlHTTP} = require('express-graphql');
var { buildSchema } = require('graphql');
// const { graphqlHTTP } = require('express-graphql');
// 请注意,它使用的解构等效于:
// const graphqlHTTP = require('express-graphql').graphqlHTTP;
var schema = buildSchema(`
type Query {
hello: String
}
`);
var root = { hello: () => 'Hello world!' };
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(3000, () => console.log('Now browse to localhost:3000/graphql'));