这就是我使用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' })
答案 0 :(得分:0)
...
app.use(bodyParser.json())
app.use('/graphql',
bodyParser.text({ type: 'application/graphql' }),
graphqlMiddleware,
graphqlExpress(req => ({
schema: schema,
rootValue: { db: req.app.locals.db }
}))
)
...