Unable to transfer image (png) using node.js and express

I studied similar questions on SO, but couldn’t find a solution for my problem ... I set up an express route for serving images, but I can’t get it to return the image from where it was stored.Note, I turned on the instruction to allow requests from any source. It happens that when I make a request for http://localhost:8080/images/x10.png, I get an empty image element with src="http://localhost:8080/images/x10.pnginstead http://ubuntubox.dev/images/x10.png, which is where the image actually is, and this is the path that I ultimately pass 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');
+4
source share
4 answers

I don’t know if you have this problem, but ..

- .pipe(res),

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');
+3

4

app.get('/images/img1.png', function(req, res){
  res.sendFile('/Absolute/path/to/the/file/images/img1.png');
});
+1

user2879041 , , ( ).

, , express.static

app.use(express.static('/Absolute/path/to/the/file/images/img1.png'));

express.static , , , ( ).

+1

, , , :

  • Create a new "public" folder and move all your assets to it.
  • Open server.js and add the following line:

app.use(express.static('public'))

Your assets should now be available as follows:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

Sure: https://expressjs.com/en/starter/static-files.html

+1
source

Source: https://habr.com/ru/post/1524773/


All Articles