Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将graphql查询结果作为文件发送?_Graphql_Graphql Js_Apollo Server_Express Graphql - Fatal编程技术网

如何将graphql查询结果作为文件发送?

如何将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

我正在使用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 = "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