3

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

enter image description here

When I run the correct node src/server/server command 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

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

2 Answers2

7

The 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'));
Community
  • 1
  • 1
Mor Paz
  • 2,088
  • 2
  • 20
  • 38
  • 1
    Thanks! :D I had to adjust my path slightly `'/../index.html'` but it works now! Hehe it's serving my index file, but without the Angular app running. So next step is figuring that out... – Leon Gaban Feb 24 '17 at 20:15
  • Glad you're making progress, be sure to mark one of the answers so users can easily use your question in the future :) – Mor Paz Feb 24 '17 at 20:18
2

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');
});