I'm trying out a hapi back end to serve up some files via HTTP GET requests. I'm a newbie with javascript but have a lot of programming experience (embedded C, Python etc..)
I have a simple method that can serve files:
server.route({
method: 'GET',
path: '/file/{param*}',
handler: {
directory: {
path: '/mydata/'
}
}
});
And this can serve up any file from /mydata/ if I know the path via: http://localhost:3000/file/hello.jpg for example
But when I create a custom method to serve up files based on a year, month and day and a string match to get a certain file I get 403 errors:
server.route({
method: 'GET',
path: '/api/getTMFile',
handler: async (request, h) => {
try {
const year = request.query.year;
const month = request.query.month;
const day = request.query.day;
if (!year || !month || !day) {
return h.response({ error: 'Missing year, month, or day parameters' }).code(400);
}
const directoryPath = Path.join(baseJmagDir, `/${year}/${month}/${day}/`);
const files = fs.readdirSync(directoryPath);
console.log('files %s', files);
// Filter files based on a specific pattern
const matchingFiles = files.filter((file) => file.startsWith('JMAG_TM_ascii_'));
if (matchingFiles.length > 0) {
// Serve the first matching file found
console.log('matching files %s', matchingFiles);
const fileToServe = Path.join(directoryPath, matchingFiles[0]);
console.log('file to serve: %s', fileToServe);
return h.file(fileToServe);
} else {
return h.response({ error: 'File not found' }).code(404);
}
} catch (error) {
console.error('Error:', error);
return h.response({ error: 'Internal Server Error' }).code(500);
}
}
});
Request: http://localhost:3000/api/getTMFile?year=2024&month=01&day=27 via Postman get 403 errors.
I have added some console logging and the code is finding the correct files at the correct path but won't serve them. It can't be a file permissions problem as I can access the file using the simple GET method so I'm wondering if this more elaborate method has some built-in security thing which I'm not disabling?
Am I missing something obvious here? Any help appreciated!