E
E
Egor2014-06-13 22:25:53
Node.js
Egor, 2014-06-13 22:25:53

Is it possible to return a stub instead of a missing image. Node.js + Express

Greetings.
I use node.js + express 4.0
Is it possible to implement such a feature. If there is no picture on the server, substitute a stub picture instead?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Chornopolsky, 2014-06-14
@ByKraB

<img src="/images/new/header1.gif" onError="this.src='error-camera.gif'">

Y
yttrium, 2014-06-13
@yttrium

it’s more correct to give statics with nginx, for example .. he knows how to give 404 man-made

Y
Yuri Gubich, 2014-06-14
@Arhangel64

I wrote this topic.
Implemented as a middver, I won’t post the code, since I myself am a teapot, and rotten vegetables will fly at me for a bydlocode, but the essence is this: the
Middlever connects before the error handler - the end of the middver chain and after the middver, which is responsible for returning statics.
The middleware checks the request, if it is an image, then the fs.stat() method reads the statistics of the stub file, the last modification time is written to the Last-Modified header. If the If-Modified-Since header is received, it is compared with the last modification time, if the header time is less, we return an empty response with a 304 status and the necessary headers.
If it is less, then the fs.pipe method gives the user a file with a status of 200 and the Last-Modified header, so that he can pass the desired header next time, so that we simply return 304.
If the stub is small, then you can wonderfully do without fs. pipe.
You can also put a tag in the If-None-Match header and catch it in the E-tag header, again, give 304 if it hasn’t changed, but my cache request mechanism worked without it. The image request time has increased from 5-8 to 7-10 ms on express 3, so I think you can do without installing an additional web server just to return such delights)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question