如何将graphql查询结果作为文件发送?
我正在使用Apollo服务器实现一个graphQL服务器。我希望将查询响应作为文本文件而不是JSON响应发送。有人能帮我在Apollo server中完成吗?我正在使用NodeJS实现服务器。使用app Express js发送文件:如何将graphql查询结果作为文件发送?,graphql,graphql-js,apollo-server,express-graphql,Graphql,Graphql Js,Apollo Server,Express Graphql,我正在使用Apollo服务器实现一个graphQL服务器。我希望将查询响应作为文本文件而不是JSON响应发送。有人能帮我在Apollo server中完成吗?我正在使用NodeJS实现服务器。使用app Express js发送文件: app.get('/URL', (req, res) => res.download('./yourFile.txt')) 并将graphql查询结果写入yourFile.txt var fs = require("fs"); var data = "y
app.get('/URL', (req, res) => res.download('./yourFile.txt'))
并将graphql查询结果写入yourFile.txt
var fs = require("fs");
var data = "your_data_graphql";
fs.writeFile("temp.txt", data, (err) => {
if (err) console.log(err);
console.log("Successfully Written to File.");
});
如果您想使用Apollo Server而不是香草
graphql
库,请尝试将插件添加到plugins
config:
const server = new ApolloServer({
typeDefs,
resolvers,
// You can import plugins or define them in-line, as shown:
plugins: [
{
requestWillStart(reqCtx) {
return {
willSendResponse(ctx) {
ctx.response.http.headers.set('Content-Disposition', 'attachment; filename=result.json');
}
}
}
}
],
})
参考资料:我的答案是否帮了你?谢谢你的回答。我确实试过这个。但是对于Apollo服务器,这不起作用。我现在给出了一个更完整的答案,但是,这在
graphqlHTTP
中是不可能的。相反,您需要原始graphql
库,或者其他一些手动查询的方法,以便我们可以(临时)将结果保存在变量中。然后,创建一个临时文件或直接作为缓冲区发送,并可选地将内容处置
头设置为附件;filename=response.json
。或者,如果可能的话,只需设置内容配置:附件;filename=result.json