I've been learning React and working on an interface where the user can view some of the files on a server using the serve-index
package and custom styling.
The relevant portion of the code is below:
app.use('/files', serveIndex(__dirname + '/files', {
stylesheet: "directory-style.css",
icons: true
}));
app.get('/files/*', (req, res) => {
res.sendFile(req.url.substr(7), {root: `${__dirname}/files`});
});
Unfortunately, if the URL is not a valid filename, the user will see an error message similar to the following:
Error: ENOENT: no such file or directory, stat 'C:\full\path\to\my\react\app\on\server'
which could be a security concern.
Is there a way to avoid exposing this full path, or should I be using an alternative to serve-index
?
I've tried enclosing various portions of the code in try-catch
blocks but to no avail.
UPDATE: I was able to resolve this issue with the following code under the file retrieval method:
app.get('/files/*', (req, res) => {
let path = req.url.substr(7);
let fileRoot = `${__dirname}/files`;
if (fs.existsSync(fileRoot + "/" + path)) {
res.sendFile(path, {root: fileRoot});
} else {
res.send(`File or directory "${path}" not found!`);
}
});