我想问您有关Node / Express中REST API的帮助。
我正在调用供应商API以获取PDF格式的标签,然后需要将其发送给正在调用API的用户。
我正在使用request
npm软件包来调用另一个API。我也尝试过node-fetch
,但是没有运气。
示例代码:
retrieveLabel(req, res, next) {
const options = {
method: 'GET',
url: 'apiUrl' + 'shipments/xxx/label',
headers: {
'cache-control': 'no-cache',
authorization: xxxToken,
'content-type': 'application/json'
}
};
request(options, (error, response, results) => {
// NO idea how to send it as reponse...
});
}
在控制台中,响应类型为string,以类似这样的开头:
%PDF-1.4
%����
3 0 obj
<
</Type /XObject /Subtype /Image /Width 1171 /Height 1676 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /Interpolate false /Filter /FlateDecode /DecodeParms<
</Predictor 12 /Colors 3 /Columns 1171 >>
/Length 61782 >>
stream
X���o�]�}'�;!Yl"�ɠh����x�H&�r�h�@(�3[ҋHK"�r+)K�q{kYL���fl���H�)��@�By�v�Ԭ\Z��3�-�5�Զ*PEJ���EU�����G�Ϲ�v���t��S��n���s�sn��>�y���1y��y��r'��Nrȝ��;�
wݓ�Ν;�m��b�X,��b�X,s�D �MO?�܊,6@rK&''w����b���266�H�%��_~��r�C���X,�e�K��������U��۲e���%+�������|���*��?pr �@�$7��In���r'��Nrȝ�0���o���|עʑ#Gn�������u�s��Z���ɓqe��|U >��9z�%�ٳw
....
答案 0 :(得分:0)
您来自API的response
是可读的流。您的res
(对来自网站客户端的http请求的响应)是可写的流。完成目标的最简单方法是将可读流通过管道写入可写对象,如下所示:
retrieveLabel(req, res, next) {
//...
request(options, (error, response, results) => {
response.pipe(res);
});
//...
您可以从流中的node documentation获取有关流管道的更多信息。