这是我的示例中的一些代码片段。它是异步的,并返回JSON对象。它可以执行任何形式的GET请求。
请注意,还有更多的最佳方法(仅作为示例)-例如,与其将放入数组的块连接起来并进行连接等,不希望将它们串联在一起。希望,它可以使您朝正确的方向开始:
const http = require('http');
const https = require('https');
/**
* getJSON: RESTful GET request returning JSON object(s)
* @param options: http options object
* @param callback: callback to pass the results JSON object(s) back
*/
module.exports.getJSON = (options, onResult) => {
console.log('rest::getJSON');
const port = options.port == 443 ? https : http;
let output = '';
const req = port.request(options, (res) => {
console.log(`${options.host} : ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
output += chunk;
});
res.on('end', () => {
let obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on('error', (err) => {
// res.send('error: ' + err.message);
});
req.end();
};
const options = {
host: 'somesite.com',
port: 443,
path: '/some/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
并提供回调函数。
例如,在服务中,我需要上面的REST模块,然后执行此操作:
rest.getJSON(options, (statusCode, result) => {
// I Could work with the resulting HTML/JSON here. I Could also just return it
console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`);
res.statusCode = statusCode;
res.send(result);
});
如果您要查找async
/await
(线性,无回调),promise,编译时支持和智能感知,我们创建了一个符合该要求的轻量级HTTP和REST客户端: