Apollo Server 2 + Express:post 处理程序缺少 req.body

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

这在版本 1 中有效,但整个服务器配置已更改。这就是我所拥有的,在按照 Daniel 在评论中的建议将 bodyparser() 添加到 express 应用程序之后:

    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()}))    
})

尽管调用了处理程序,但请求 body 从未到达 app.post 处理程序。不过,我看到它从浏览器中消失了。有什么想法吗?

更新: 丹尼尔的答案是正确的,但是我在使用 headers 的请求中遇到了另一个问题。一旦我解决了这个问题,post 处理程序就会收到 body。

Apollo 的中间件将 bodyparser 中间件专门应用于 GraphQL 端点——它不会影响您的服务器公开的任何其他路由。为了正确填充req.body,需要自己添加bodyparser中间件,例如:

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

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

我也刚 运行 喜欢这个。通过将以下内容传递到 headers:

来修复它
Content-Type: application/json