我正在使用node-libcurl与我的应用程序接口通信,它应该返回一个普通的JSON响应。我使用了以下代码:
// cURL instance
const curl = new Curl();
const close = curl.close.bind(curl);
// cURL Options
curl.setOpt(Curl.option.URL, 'http://locally-hosted/consume.endpoint');
curl.setOpt(Curl.option.CONNECTTIMEOUT, 60);
curl.setOpt(Curl.option.FOLLOWLOCATION, true);
curl.setOpt(Curl.option.VERBOSE, true);
// Custom headers for this request
curl.setOpt(Curl.option.HTTPHEADER, [
'Some: Value'
]);
// POST payload
curl.setOpt(Curl.option.POSTFIELDS, querystring.stringify({
id: 1,
value: 'foobar'
}));
// cURL cookie settings
const cookieJarFile = path.join(__dirname, 'cookiejar.txt');
curl.setOpt(Curl.option.COOKIEFILE, cookieJarFile);
curl.setOpt(Curl.option.COOKIEJAR, cookieJarFile);
// Cookie jar file check
if (!fs.existsSync(cookieJarFile)) {
fs.writeFileSync(cookieJarFile);
}
// Event listener for data
curl.on('data', (chunk, curlInstance) => {
console.log('Receiving data with size: ', chunk.length);
console.log(chunk.toString());
});
// Event listener for end
curl.on('end', (statusCode, body, headers, curlInstance) => {
console.info('Status Code: ', statusCode);
console.info('Headers: ', headers);
console.info('Body length: ', body.length);
console.info('Body: ', body);
curl.close();
});
// Error handler for cURL
curl.on('error', (error, errorCode) => {
console.error('Error: ', error);
console.error('Code: ', errorCode);
curl.close();
});
// Commits this request to the URL
curl.perform();我在data事件侦听器中或在end事件侦听器完成时获得响应。我面临的问题是,我在这个表示中得到了响应:
Body: �w[��x��%Yl��(|�q-�.
M$�kネ���A@\��eǽ�>B�E��
m�
-�也就是说,我认为这是一个二进制响应,但我无法将其转换为任何合理的值。应用.toString()无济于事,而且,如果您检查data事件侦听器,我会在那里说:chunk.toString(),它返回给我同样的东西。
如何使用Node.js的cURL获取文本正文响应?
发布于 2020-11-27 17:39:29
https://stackoverflow.com/questions/59125015
复制相似问题