node.js - Stream Response into HTTP Response -
i have api trying make http request api streams , image me, either stream image client making request me or wait until image has been streamed me , send @ once.
i using express , request-promise.
here's shortened version of code.
const express = require('express'); const router = express.router(); const request = require('request-promise'); const imgfunc = async () => { try { const response = await request.get({ method: 'get', uri: `http://localhost:8080`, }); return response; } catch(err) { console.log(err); } }; router.get('/', async function(req, res, next) { try { const response = await imgfunc(); return res.send(response); } catch (err) { console.log(err); } }); module.exports = router;
the image assume binary data , don't know if need @ request-promise level make right or when send client.
the server have running @ localhost:8080 mimics actual server hitting when said , done.
you pipe streams directly rather using request-promise
.
const express = require('express'); const router = express.router(); const https = require('https'); router.get('/', function(req, res) { const url = 'https://www.gravatar.com/avatar/2ea70f0c2a432ffbb9e5875039645b39?s=32&d=identicon&r=pg&f=1'; const request = https.get(url, function(response) { const contenttype = response.headers['content-type']; console.log(contenttype); res.setheader('content-type', contenttype); response.pipe(res); }); request.on('error', function(e){ console.error(e); }); }); module.exports = router;
or using request
library on request-promise
based:
const express = require('express'); const router = express.router(); const request = require('request'); router.get('/', function(req, res) { const url = 'https://www.gravatar.com/avatar/2ea70f0c2a432ffbb9e5875039645b39?s=32&d=identicon&r=pg&f=1'; request.get(url).pipe(res); }); module.exports = router;
Comments
Post a Comment