Home > Mobile >  Why can't res.sendFile access __dirname "/../public" if the script calling the func
Why can't res.sendFile access __dirname "/../public" if the script calling the func

Time:10-10

I have the following folder structure:

public/
   bug-reporter/
      bugs.html
src/
   bug-reporter.js
app.js

If I do this from app.js, it works fine:

// app.js
app.use(express.static(__dirname))
app.use(express.static(__dirname   '/public'))

app.get('/bug-reporter/', (req, res) => res.sendFile(__dirname   '/public/bug-reporter/bugs.html')

But if do this:

// app.js
const bugReporter = require('./src/bug-reporter')
app.get('/bug-reporter/', bugReporter.home)

// bug-reporter.js
exports.home = ((req, res) => res.sendFile(__dirname   '/../public/bug-reporter/bugs.html'))

In the console I get error ForbiddenError: Forbidden.

CodePudding user response:

You should use path.resolve

exports.home = ((req, res) => res.sendFile(path.resolve(__dirname, '../public/bug-reporter/bugs.html')))

Because .. is not allowed in absolute paths

  • Related