Apollo Server 2 + Express:后处理程序上缺少必需的实体

时间:2018-10-11 00:23:22

标签: graphql apollo-server

此功能在版本1中有效,但整个服务器配置已更改。这就是我在丹尼尔在评论中建议的将bodyparser()添加到快速应用程序后得到的:

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

尽管请求处理程序被调用,但请求主体从未将其传递给app.post处理程序。我看到它从浏览器中消失了。有什么想法吗?

更新:Daniel的回答正确,但是我使用的请求标头中存在另一个问题。一旦我解决了问题,邮递员便收到了尸体。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

我也碰到了这个。通过将以下内容传递到标题中来解决此问题:

Content-Type: application/json