【发布时间】:2018-05-05 02:12:09
【问题描述】:
这就是我使用 bodyParser 作为 expressJS/graphQL 服务器的中间件的方式。
const graphqlMiddleware = [
// bodyParser is needed just for POST.
bodyParser.json(),
bodyParser.text({ type: 'application/graphql' }),
(req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
if (req.is('application/graphql')) {
req.body = { query: req.body }
}
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
}
]
app.use('/graphql',
...graphqlMiddleware,
graphqlExpress(req => ({
schema: schema,
rootValue: { db: req.app.locals.db }
}))
)
现在我试图重组我的文件,所以我把函数移到了
/middlewares/graphql.js
module.exports = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
if (req.is('application/graphql')) {
req.body = { query: req.body }
}
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
}
...并将其导入我的入口点:
app.js
import graphqlMiddleware from './middlewares/graphql'
app.use('/graphql',
graphqlMiddleware,
graphqlExpress(req => ({
schema: schema,
rootValue: { db: req.app.locals.db }
}))
)
但是我应该如何(以及在哪里)添加 bodyParser?
bodyParser.json(),
bodyParser.text({ type: 'application/graphql' })
【问题讨论】:
标签: javascript express graphql