I used graphql and koa2.
const Koa = require('koa')
const json = require('koa-json')
const bodyparser = require('koa-bodyparser')
const config = require('./config')
const port = config.URL.port
const cors = require('@koa/cors')
const UserRoute = require('./routes/user.router')
const { ApolloServer, gql } = require('apollo-server-koa')
const app = new Koa()
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`
const resolvers = {
Query: {
books: () => books,
},
}
app.use(cors({
origin: '*',
credentials: true,
methods: ['PUT', 'POST', 'GET', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Content-Length', 'Authorization', 'Accept', 'X-Requested-With', 'x-access-token']
}))
app.use(UserRoute.routes(), UserRoute.allowedMethods())
app.use(bodyparser())
app.use(json())
const server = new ApolloServer({ typeDefs, resolvers })
server.applyMiddleware({
app,
path: config.URL.graphql,
})
module.exports = app.listen(port)
I just want to use graphql on some of the interfaces.


I use postman for debugging. Any good suggestions?
@BengBu-YueZhang All you need is a custom middleware:
...
const Koa = require('koa')
const raw = require('raw-body');
const inflate = require('inflation');
const app = new Koa();
...
app.use(async (ctx, next) => {
if (ctx.req.headers['content-type'] === 'application/graphql') {
const str = await raw(inflate(ctx.req), { encoding: 'utf8' });
ctx.request.body = { query: str };
}
await next();
});
By this middleware, the content-type application/graphql will work in expectation.
Or you can use the package koa-bodyparser-graphql directly.
@yvanwangl 非常感谢您的帮助,我已经解决了这个问题。之前在dva的开源社区里就见过您的作品,没想到能在这里遇见你。再次感觉,已经对您的项目star和fork了
Koa-bodyparser-graphql solves my problem, very cool
Can we get the docs updated that this is not handled by default?
Quite misleading and I would have saved time instead of trying to get it to work.
If the "application/graphql" Content-Type header is present, treat the HTTP POST body contents as the GraphQL query string.
Most helpful comment
Or you can use the package
koa-bodyparser-graphqldirectly.