问题描述
我正在使用库 apollo-datasource-rest
,但在尝试获取内容时收到错误:
const req = await this.get(uri);
const data = await req.json(); // Error here
// I tried to use .text() too and I received the same error:
我收到的错误是这样的:
body used already for: http://<endpoint>
TypeError: body used already for: http://<endpoint>
at Response.consumeBody (/opt/app/node_modules/node-fetch/lib/index.js:343:30)
at Response.text (/opt/app/node_modules/node-fetch/lib/index.js:283:22)
at MyApi.u003canonymousu003e (/opt/app/src/api/api.ts:20:24)\\n at Generator.next (u003canonymousu003e)
at fulfilled (/opt/app/dist/api/api.js:5:58)
at processticksAndRejections (internal/process/task_queues.js:93:5)"
我知道当尝试两次或更多次获取请求正文时,此错误会发生在 node-fetch
中,例如:
const fetch = require('node-fetch');
const req = await fetch('http://.....');
const data1 = await req.json();
const data2 = await req.json(); // <- The error happen here
但是,在我的代码中我没有第二个调用,在第一个调用中我收到错误:/
这是我的代码(更改为隐藏我的公司数据):
class MyAPI extends RESTDataSource {
async myGetCall(): Promise<MyDataDTO> {
const uri = '/my/path';
const req = await this.get(uri);
let body = '';
try {
body = await req.text(); // Error here. I tried with .json() too
} catch (e) {
this.logger.error(`Unexpected parse data from api with status: ${req.status}`,e);
}
if (req.status >= 200 && req.status < 300) {
return body;
}
throw new Error(`Error getting data. Api status: ${req.status} with body: ${body}`);
}
附加信息,我将替换方法 willSendRequest
和 didReceiveResponse
以获取普罗米修斯的指标。但我认为这不是问题。
// ....
willSendRequest(request: RequestOptions) {
const requestId = uuidv4();
request.headers.set('RequestID',requestId);
histograms.set(requestId,promClient.httpHistogram());
timers.set(requestId,new Date());
}
didReceiveResponse(response: any,request: Request) {
const requestId = request.headers.get('RequestID');
const method = request.method.toupperCase();
const { status } = response;
const url = (response.url || '').split('?')[0];
const urlObject = new URL(url);
try {
histograms.get(requestId)({
method,url,statusCode: status,hostname: urlObject.hostname,});
this.logger.info(`dataSource: ${method}: ${url} in ${new Date().getTime() - timers.get(requestId)}ms - status: ${status}`);
timers.delete(requestId);
histograms.delete(requestId);
} catch (e) {
// eslint-disable-next-line
this.logger.error(`Error creating histogram: ${JSON.stringify(response)}`,e);
}
return response;
}
只有在我收到太多请求时才会在生产中发生这种情况。 如果我在本地主机上运行,一切正常
我认为可能是 HttpCache 的一些问题(我没有配置)
有人可以帮我吗?我不知道我的代码会发生什么:/
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)