[Solved-2 Solutions] Express res.sendfile throwing forbidden error



Error Description:

    • We have this code:
    res.sendfile( '../../temp/index.html' )
     
    click below button to copy the code. By - nodejs tutorial - team
    • However, it throws this error:
    Error: Forbidden
    at SendStream.error (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/send/lib/send.js:145:16)
    at SendStream.pipe (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/send/lib/send.js:307:39)
    at ServerResponse.res.sendfile (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/response.js:339:8)
    at exports.boot (/Users/Oliver/Development/Personal/Reader/server/config/routes.js:18:9)
    at callbacks (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:161:37)
    at param (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:135:11)
    at pass (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:142:5)
    at Router._dispatch (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:170:5)
    at Object.router (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:33:10)
    at next (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/connect/lib/proto.js:199:15)
    
     
    click below button to copy the code. By - nodejs tutorial - team

    Solution 1:

      • It's because of the relative path; the "../" is considered malicious. Resolve the local path first, then call res.sendfile. You can resolve the path with path.resolve beforehand.
      var path = require('path');
      res.sendFile(path.resolve('temp/index.html'));
      
       
      click below button to copy the code. By - nodejs tutorial - team

      Solution 2:

        • The Express documentation suggests doing it a different way:
        res.sendFile('index.html', {root: './temp});
         
        click below button to copy the code. By - nodejs tutorial - team
        • The root option seems to set ./ as the root directory of your project. So we cannot tell where the file is in relation to the project root, but if your temp folder is there, you can set ./temp as the root for the file you're sending.

        Related Searches to Express res.sendfile throwing forbidden error