向Apollo Server发送含operationName与variables的POST请求技术咨询
Apollo Server POST 请求测试问题咨询
我正在尝试向 Apollo Server 发送包含 operationName 和 variables 参数的 POST 请求,参考官方文档编写了测试代码,现在遇到了一些技术问题,想向大家请教。
我的测试代码
it('should get author correctly', () => { const body = { query: ` query { getAuthor($id: Int!) { name } } `, // operationName: 'query author', variables: { id: 1 } }; return rp.post(body).then(res => { expect(res.data.getAuthor.name).to.equal('lin'); }); });
用到的 rp.js 片段
const requestPromise = require('request-promise'); const { PORT } = require(...); // 这里省略了后续的导入内容
我梳理出的问题及修正建议
- GraphQL 查询语法错误:你的查询里变量定义的位置不对,应该把变量放在 query 名称后的括号里,同时要在字段调用时传入变量。正确的查询写法应该是:
query GetAuthor($id: Int!) { getAuthor(id: $id) { name } } - operationName 设置问题:如果你的查询定义了名称(比如上面的
GetAuthor),operationName就应该和这个名称一致,而不是query author,所以可以把注释去掉,改成:operationName: 'GetAuthor' - request-promise 调用错误:
rp.post()不能直接传请求体,需要指定请求的 URL、设置json: true等选项,否则请求无法正确发送到 Apollo Server。修正后的请求代码应该类似这样:return rp.post({ url: `http://localhost:${PORT}/graphql`, // 替换成你的 Apollo Server 实际地址 body: body, json: true }).then(res => { expect(res.data.getAuthor.name).to.equal('lin'); });
如果还有具体的错误返回信息(比如接口报错内容),可以补充出来,这样能更精准地定位问题~
内容的提问来源于stack exchange,提问作者Lin Du
相关产品推荐
相关产品推荐

