Proper way to render error page (404...)



  • Hello !

    I'm writing a plugin where I do this :

    app.get('/uploads/myfiles/:file(*?)', function (req, res) {
    		// Things TODO with req.params.file for permissions (after work on it)...
    		var longfilename = path.resolve('public' + req.url);
    		if (fs.existsSync(longfilename)) {
    			res.status(200);
    			res.sendFile(longfilename);
    		} else {
    			console.log('Fichier non trouvé');
    			res.status(404);
    			res.render('404', {path: req.path});
    		}
    	});
    

    When a file is not found, I return a 404 error page with the last "else". It works in a ugly way because of no 404.tpl file... How can I call a standard nodebb error page for this 404 error ? What is the good res.render command (or else) ?


  • Staff Admin

    @alfazaz said in Proper way to render error page (404...):

    app.get('/uploads/myfiles/:file(*?)', function (req, res) {
    // Things TODO with req.params.file for permissions (after work on it)...
    var longfilename = path.resolve('public' + req.url);
    if (fs.existsSync(longfilename)) {
    res.status(200);
    res.sendFile(longfilename);
    } else {
    console.log('Fichier non trouvé');
    res.status(404);
    res.render('404', {path: req.path});
    }
    });

    The proper way is to call next and let the core 404 handler do it's magic.

    app.get('/uploads/myfiles/:file(*?)', function (req, res, next) {
    		// Things TODO with req.params.file for permissions (after work on it)...
    		var longfilename = path.resolve('public' + req.url);
    		if (fs.existsSync(longfilename)) {
    			res.status(200);
    			res.sendFile(longfilename);
    		} else {
     			next();
    		}
    	});
    


  • @baris Thanks !!


Log in to reply
 

Suggested Topics

  • 1
  • 6
  • 1
  • 12
  • 1
| |