Here is my folder structure:
I have everything inside the src
folder, src/index.html
is what I'm trying to point too. And my node server file is in src/server/server.js
When I run the correct node src/server/server
mand I get the following error:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname });
});
app.get('/category', (req, res) => {
res.end('Categories');
});
app.listen(8999, (res) => {
console.log(res);
});
Error: ENOENT: no such file or directory, stat '/Users/leongaban/Projects/CompanyName/appName/src/server/index.html'
So the error message is telling me I need to go 1 more folder up, so figured something like the following:
app.get('/', (req, res) => {
res.sendFile('../index.html', { root: __dirname });
});
However now I get a Forbidden error:
ForbiddenError: Forbidden
Here is my folder structure:
I have everything inside the src
folder, src/index.html
is what I'm trying to point too. And my node server file is in src/server/server.js
When I run the correct node src/server/server
mand I get the following error:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname });
});
app.get('/category', (req, res) => {
res.end('Categories');
});
app.listen(8999, (res) => {
console.log(res);
});
Error: ENOENT: no such file or directory, stat '/Users/leongaban/Projects/CompanyName/appName/src/server/index.html'
So the error message is telling me I need to go 1 more folder up, so figured something like the following:
app.get('/', (req, res) => {
res.sendFile('../index.html', { root: __dirname });
});
However now I get a Forbidden error:
Share Improve this question asked Feb 24, 2017 at 20:05 Leon GabanLeon Gaban 39.1k122 gold badges349 silver badges550 bronze badgesForbiddenError: Forbidden
2 Answers
Reset to default 7The reason you get a Forbidden
error is because Node.js finds the relative path ../
malicious (for example if you get a file based on user input he might try to reach files on your file system which you don't want him to access).
so instead you should use the path module like pointed in this question
Your code should use path like so:
var path = require('path');
res.sendFile(path.resolve(__dirname + '../index.html'));
I had a similar problem with a mean stack problem earlier on.
Mor Paz' above answer should work. :)
Just to contribute, i did the following.
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile('../index.html');
});