23
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

express-graphqlで出たエラーにはまった

Last updated at Posted at 2020-08-05

何をしようとしたか

GraphQL + Express JS + MongoDBの環境構築をしようと思いました。
しかしサーバーの起動ではまることに。

本題

mongooseを使ってmongoDBと接続。
またapp.useのハンドラー部分にgraphqlHTTPを指定します。
一見大丈夫そう。

//app.js

const express = require('express')
const graphqlHTTP = require('express-graphql')
const mongoose = require('mongoose')
const app = express()

mongoose.connect('mongodb+srv://testuser001:password@cluster0.fpkid.mongodb.net/my_db?retryWrites=true&w=majority')
mongoose.connection.once('open', () => {
  console.log('db connected')
})

app.use('/graphql', graphqlHTTP({

}));
app.listen(4000, () => {
  console.log('listening 4000')
})

しかしnodemon appでサーバーを立ち上げると、graphqlHTTPのところでエラーがでました。

$ nodemon app
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
graphql_dir/server/app.js:14
app.use('graphql', graphqlHTTP({
                   ^

TypeError: graphqlHTTP is not a function
    at Object.<anonymous> (/graphql_dir/server/app.js:14:20)

なにがダメなのかさっぱり分からず30分ほどはまる。

解決

こちらに使い方がしっかりと書いてありました。

// 正解
const { graphqlHTTP }  = require('express-graphql')

つまり下記と同義なんですよね。


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

graphqlHTTPが記述されているファイルの中身をまんま渡していたようです。

修正し、再びnodemon appでサーバーを起動。
無事mongoDBにも接続できました!

$ nodemon app
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
(node:13225) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(Use `node --trace-deprecation ...` to show where the warning was created)
listening 4000
(node:13225) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
db connected

あとがき

とはいえ、const graphqlHTTP = require('express-graphql')のように記述している記事をいくつか見かけています。
間違ってるのか、それでうまく行くのかは分かりませんが、もしエラーが出たら参考にしてください。

23
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?