Reputation: 135
import express from "express"
import path from "path"
const app = express();
const __dirname = path.resolve();
app.use(express.static(`${__dirname}/../'webapp_test`)) //ERROR
app.get(`/`,(req,res)=>{
res.sendFile(`${__dirname}/../webapp_test/todo.html`);
});
app.listen(8080);
By setting express.static() path as string literal with escape sequence ${}
Error occurs when connect to localhost:8080
like
ForbiddenError: Forbidden
at SendStream.error (WORKING DIRECTORY\node_modules\send\index.js:270:31)
at SendStream.pipe (WORKING DIRECTORY\node_modules\send\index.js:553:12)
at sendfile (WORKING DIRECTORY\node_modules\express\lib\response.js:1103:8)
at ServerResponse.sendFile (WORKING DIRECTORY\node_modules\express\lib\response.js:433:3)
at file://WORKING DIRECTORY/main.js:13:9
at Layer.handle [as handle_request] (WORKING DIRECTORY\node_modules\express\lib\router\layer.js:95:5)
at next (WORKING DIRECTORY\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (WORKING DIRECTORY\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (WORKING DIRECTORYt\node_modules\express\lib\router\layer.js:95:5)
at WORKING DIRECTORY\node_modules\express\lib\router\index.js:281:22
But if I set path with path.join
method as
app.use(express.static(path.join(__dirname,`..`,`webapp_test`));
app.get(`/`,(req,res)=>{
res.sendFile(path.join(__dirname,`..`,`webapp_test`,`todo.html`));
});
Page loads well
What am I missing?
Upvotes: 1
Views: 283
Reputation: 86
It is because of the "../". This is considered malicious and will be blocked by express in order to prevent web users from theoretically accessing the computers file system by typing .. In the url. You need to resolve the path first by calling path.resolve and then the whole computers file s pass it to express. This is essentially what path.join also does so that after calling path.join it also works.
That means you need to replace
res.sendFile(`${__dirname}/../webapp_test/todo.html`);
with
res.sendFile(path.resolve(`${__dirname}/../webapp_test/todo.html`));
As well as
app.use(express.static(`${__dirname}/../'webapp_test`)) //ERROR
with
app.use(express.static(path.resolve(`${__dirname}/../webapp_test`))) //ERROR
Another solution would be to specify the root directory for your calls like ths :
res.sendfile(path, {'root': '/path/to/root/directory'});
Hope that anwsers your question.
Upvotes: 1