所以我正在使用 Next JS API 路由,在其中一个路由中,我使用 Apollo 调用 GraphQL 突变,例如:
// pages/api/foo.js
import { initializeApollo } from '~/server/apollo'
export default function handler(req, res) {
const client = initializeApollo()
try {
await client.mutate({ mutation: FooDocument })
// this works
res.status(200).send({ foo: '...' })
} catch {
// this fails
res.status(500).send({ error: '...' })
}
}
如您所见,如果突变失败,我在调用
res.status(500).send({ error: '...' })
时收到服务器错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
但是如果突变成功,我在调用
res.status(200).send({ foo: '...' })
时没有错误。
有谁知道为什么会这样?我想我最好的选择是只在前端调用这个突变,但我想知道是否有办法解决这个问题。