graphqlHTTP is not a function

荒凉一梦 提交于 2020-07-16 02:22:28

问题


Here is my simple graphql experess app

const express = require('express');
const graphqlHTTP = require('express-graphql');

const app = express();
app.use(
    '/graphql',
    graphqlHTTP({
      graphiql: true,
    })
  );

app.listen(4000, () => {
    console.log("listening for request!");
});

I'm getting the following errors when I run it:

 graphqlHTTP({
    ^

TypeError: graphqlHTTP is not a function
    at Object.<anonymous> (D:\PersonalProjects\GraphQL\server\app.js:7:5)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)  
    at internal/main/run_main_module.js:17:47

How can I fix it? Thanks in advance!


回答1:


Look at the documentation:

const { graphqlHTTP } = require('express-graphql');

Note that it uses destructuring equivalent to:

const graphqlHTTP = require('express-graphql').graphqlHTTP;

require('express-graphql') returns an object with a property called graphqlHTTP that is the function you want to call.

You're trying to call the object itself as if it was a function.




回答2:


Quentin's answer was on spot. Apparently the npm documentation was updated but some of the tutorials on YouTube were not. That's why there's a certain degree of confusion for learners like myself. There are still outdated versions of the code like

This one: https://github.com/iamshaunjp/graphql-playlist/blob/lesson-36/server/app.js

This one: https://github.com/WebDevSimplified/Learn-GraphQL/blob/master/server.js

Or this one: https://github.com/bradtraversy/customerbase/blob/master/server.js

They should all be updated to

const { graphqlHTTP } = require('express-graphql');

and then

app.use('/graphql', graphqlHTTP({
    schema:schema,
    graphiql:true
}));


来源:https://stackoverflow.com/questions/62760975/graphqlhttp-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!