Jef*_*ery 3 graphql apollo-server
在版本 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()}))
})
Run Code Online (Sandbox Code Playgroud)
尽管调用了处理程序,但请求正文永远不会到达 app.post 处理程序。不过,我看到它是从浏览器中发出的。有任何想法吗?
更新: 丹尼尔有正确的答案,但我在使用的请求标头中遇到了另一个问题。一旦我解决了这个问题,邮件处理程序就会收到正文。
Apollo 的中间件将 bodyparser 中间件专门应用于 GraphQL 端点——它不会影响服务器公开的任何其他路由。为了正确填充req.body,您需要自己添加 bodyparser 中间件,例如:
app.use(bodyParser.json())
app.post('/calc', routeHandler)
// or...
app.post('/calc', bodyParser.json(), routeHandler)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2883 次 |
| 最近记录: |