I've studied similar questions on SO but haven't found a solution to my problem... I've set up an express route to serve images but I can't get it to return an image from where it's stored. Notice I've included a statement to allow requests from any origin. What happens is that when I make a request to http://localhost:8080/images/x10.png
the response I get is an empty image element with src="http://localhost:8080/images/x10.png
instead of from http://ubuntubox.dev/images/x10.png
, which is where the image is actually located and is the path I'm ultimately passing to the request method. What am I missing? Thanks.
app.get('/images/*', function(req, res, path){
var imagePath = req.url,
url = 'http://ubuntubox.dev' + imagePath;
request(url, function(error, response, img) {
if(!error && response.statusCode === 200) {
res.header('Access-Control-Allow-Origin', '*');
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(img, 'binary');
} else if(response.statusCode === 404) {
res.status(404);
res.type('txt').send('oops');
}
});
}).listen(8080, '127.0.0.1');
Open the local page http://127.0.0.1:2000/ to upload the images. Select an image to upload and click on "Upload Image" button. Here, you see that file is uploaded successfully. You can see the uploaded file in the "Uploads" folder.
createServer(function (req, res) { res. writeHead(200, {'Content-Type': 'text/html'}); fs. readFile('image. jpg', function (err, data) { if (err) throw err; res.
I don't know if you still have this problem, but..
The solution for your problem is just putting a .pipe(res) and it will send the file to the response
app.get('/images/*', function(req, res, path){
var imagePath = req.url,
url = 'http://ubuntubox.dev' + imagePath;
request(url).pipe(res);
}).listen(8080, '127.0.0.1');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With