I'm serving static files with Express like this:
app.use('/uploads/users/images', express.static(path.join(__dirname, 'uploads', 'users/images')));
But these files don't show on my frontend application, instead this error message shows up
The resource at “http://localhost:8080/uploads/users/images/1670518070063.jpg” was blocked due to its Cross-Origin-Resource-Policy header (or lack thereof). See https://developer.mozilla.org/docs/Web/HTTP/Cross-Origin_Resource_Policy_(CORP)#
I'm also using the cors dependency from npm in this way
app.use(cors({ origin: '*' }))
...
...
route definitions
CodePudding user response:
I read more about this HTTP header in the MDN web docs here, and found that this header can have the next values (same-site, same-origin, and cross-origin).
I fixed the error by setting the header manually in my uploads route:
app.use('/uploads', (_, res, next) => {
res.set('Cross-Origin-Resource-Policy', 'cross-origin');
next();
})
...
app.use('/uploads/users/images', express.static(path.join(__dirname, 'uploads', 'users/images')));
Although there is a warning due to a bug in Chrome when serving PDF files
CodePudding user response:
I don't recall having to configure CORS at all the last time I stoof up Express and used it to serve static files. The documentation say to do it like this:
app.use(express.static('public'))
or this
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))