ApolloServer(NodeJS)如何针对特定GET请求直接返回字符串响应?
解决办法
方法一:通过Apollo Server插件拦截请求
Apollo Server的插件系统可以在请求生命周期早期介入,直接返回自定义响应,无需走网关转发流程。修改你的ApolloServer配置,添加如下插件:
const server = new ApolloServer({ debug: false, gateway, context: async ({req}) => { // 保留原context逻辑 }, plugins: [ { async requestDidStart() { return { async parsingDidStart(requestContext) { // 根据实际需求判断目标GET请求,比如路径、查询参数 const { req } = requestContext.context; if (req.method === 'GET' && req.path === '/your-target-path') { // 直接构造并返回自定义响应 requestContext.response = { http: { status: 200, headers: new Headers({ 'Content-Type': 'text/plain', }), body: "someString" } }; // 返回null终止后续请求流程 return null; } } }; } } ] });
方法二:用底层HTTP框架中间件拦截(以Express为例)
如果你的Apollo Server挂载在Express上,可以在Apollo中间件前添加自定义中间件,提前拦截目标请求:
const express = require('express'); const app = express(); // 拦截特定GET请求直接返回字符串 app.get('/your-target-path', (req, res) => { res.status(200).send("someString"); }); // 挂载Apollo Server server.applyMiddleware({ app }); app.listen({ port: 4000 }, () => { console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`); });
原方法失效的原因
你重写的didReceiveResponse是RemoteGraphQLDataSource的方法,它仅在网关将请求转发到子服务并收到响应后才会触发,作用是修改子服务返回的数据。而你需要的是直接返回字符串,不需要转发到子服务,所以这个方法根本不会被执行,自然无法生效。
内容的提问来源于stack exchange,提问作者Seeker
相关产品推荐
相关产品推荐

