我正在尝试从仅返回文本字符串((here))的API抓取文本,并且在将其扔出响应时遇到麻烦。发布时,其显示为[object Response]
,而console.log
未显示我想要的文本。
我正在使用的代码:
fetch('http://taskinoz.com/gdq/api').then(
function(response) {
console.log(response);
throttledSendMessage(channel, response);
return response;
})
.catch(function(error) {
throttledSendMessage(channel, "An error has occured");
})
日志可以为found here
感谢与我一起寻找,找不到解决方法:/
答案 0 :(得分:6)
我认为因为v_someview = Table(
'someview', metadata,
Column('dt', TIMESTAMP()),
Column('wk_begin', TIMESTAMP(),ForeignKey("WeeknumTable.dt")),
Column('iwp', Float(53)),
schema='ww',
week_begin = relationship(WeeknumTable)
返回一个Response
,所以您需要调用fetch
上的一个函数才能获取正文。这是一个示例:
Response
答案 1 :(得分:1)
Fetch
在nodejs中不可用,您可以使用node-fetch
https://www.npmjs.com/package/node-fetch,也可以使用以下fetch
函数:
const https = require('https');
const http = require('http');
function fetch(url, options = {}) {
return new Promise((resolve, reject) => {
if (!url) return reject(new Error('Url is required'));
const { body, method = 'GET', ...restOptions } = options;
const client = url.startsWith('https') ? https : http;
const request = client.request(url, { method, ...restOptions }, (res) => {
let chunks = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
chunks += chunk;
});
res.on('end', () => {
resolve({ statusCode: res.statusCode, body: chunks });
});
});
request.on('error', (err) => {
reject(err);
});
if (body) {
request.setHeader('Content-Length', body.length);
request.write(body);
}
request.end();
});
}
module.exports = fetch;
您可以在代码中像这样使用它:
const result = await fetch(
`https://YOUR_URL`,
{
method: 'PUT',
body: JSON.stringify({ test: 'This is just a test', prio: 1 }),
},
);
答案 2 :(得分:0)
问题可能出在node.js的异步行为中。您可以阅读更多here
另外,我假设您使用this包在node.js中进行提取请求。
并假设throttledSendMessage
函数是同步的。
关于您的问题,只需尝试重写代码以将async / await用于更干净的解决方案即可。
// We'll use IIFE function
(async () => {
const fetchResult = await fetch('http://taskinoz.com/gdq/api')
// Here fetch return the promise, so we need to await it again and parse according to our needs. So, the result code would be this
const data = await fetchResult.text();
throttledSendMessage(channel, data);
return data;
})()