最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to point Node server to serve an index file 1 path up? - Stack Overflow

programmeradmin4浏览0评论

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:

ForbiddenError: Forbidden

Share Improve this question asked Feb 24, 2017 at 20:05 Leon GabanLeon Gaban 39.1k122 gold badges349 silver badges550 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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'));

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');
});
发布评论

评论列表(0)

  1. 暂无评论