Images url served by express doesn't load when putting it in the <img /> tag on html page another server

Viewed 21

Images url served by express doesn't load when putting it in the img tag on another server.

-- the image url i serve from express here: https://gardennotes.herokuapp.com/api/img/users/default.jpeg

-- if you visit this link the image will load in the browser normally.

-- but if you put it in the html tage img it will not load unless the html tag img is inside html page on the same server that serving the api

-- The following line of code is from express , that responsble for serving the image.

app.use('/api/img', express.static(path.join(__dirname, 'img')));

hope any one has the solution, i have been trying to fix it for two days

1 Answers

A good place to start when debugging an issue, as suggested in the comments, is to take a look at the browser console or other DevTools to see what may be happening.

In this instance, in Firefox:

screenshot of error in Firefox DevTools

The message suggests reading into the documentation on "Cross-Origin Resource Policy". This header allows the server to specify if servers should be able to access resources "cross-origin," or from a server that isn't the one serving the resource.

In this case, it sounds like you would like this file to be accessible cross-origin. Therefore, we must set the Cross-Origin-Resource-Policy header to allow cross-origin requests. For example:

app.use(express.static('public', {
    setHeaders: (res, path, stat) => {
        res.set('Cross-Origin-Resource-Policy', 'cross-origin');
    },
});
Related