graphqlapollo-server

Apollo Server 2 + Express: req.body missing on post handler


Had this working in version 1, but the whole server config has changed. This is what I have, after adding bodyparser() to the express app as was suggested by Daniel in the comments:

    const server = new ApolloServer({
    typeDefs,
    resolvers,
    playground: {
        settings: {
            'editor.theme': 'light',
        }
    },
})

// Initialize the app
const app = express();
app.use(cors())
app.use(bodyParser.json())

server.applyMiddleware({
    app
})

app.post('/calc', function(req, res){
    const {body} = req;

    console.log("HOWDYHOWDYHOWDY", body) // <== body is {}

    res.setHeader('content-type', 'application/json')

    calculate(body)
        .then(result => res.send(result))
        .catch(e => res.status(400).send({error: e.toString()}))    
})

The request body is never making it to the app.post handler, though the handler is called. I see it going out from the browser, though. Any ideas?

Update: Daniel had the correct answer, but I had another problem in the request headers I was using. Once I fixed that, then the post handler received the body.


Solution

  • Apollo's middleware applies the bodyparser middleware specifically to the GraphQL endpoint -- it won't affect any other routes your server exposes. In order to correctly populate req.body, you need to add the bodyparser middleware yourself, for example:

    app.use(bodyParser.json())
    app.post('/calc', routeHandler)
    
    // or...
    app.post('/calc', bodyParser.json(), routeHandler)