How to bring an image of a website in the Node API request?

Asked

Viewed 199 times

0

I’m making an application and wanted after giving a request, that the API bring an image of this website as an answer. For example, in giving error 404, I would like you to bring that.

How can I do?

I currently have a method of this:

app.use((req, res, next) => {
    const error = new Error('Não há nada aqui :c');
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            mensagem: error.message
        }
    })
});
  • 1

    Have you looked at the documentation of response object of Expressjs? There is a method for sending files that can serve what you need.

  • @Gustavosampaio already looked yes face, but for being new in this world, I could not find a right answer!

1 answer

1


The only way I could find it was this:

app.use((error, req, res, next) => { 
    res.status(error.status || 500); 
    res.send(`<img src="http://http.cat/${error.status || 500}" />`); 
});

That is, he sends an element as an answer <img>, having the attribute src with the website image link, according to the error code.

If you want, you can add the style element, letting the image occupy the entire screen:

res.send(`<img src="http://http.cat/${error.status || 500}" style="width:100%;" />`); 

The res.sendFile would not be suitable for that occasion

The res.sendFile only works to send files that are on the same server. And that way, there would be no way to add the image link as a file path, as it would return an error of "non-existent file".

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.