enricosapicco enricosapicco - 1 month ago 6
Node.js Question

Reaching html file in another subfolder express.js

My folder hierarchy is as follows;





when I run the code

var express = require('express');
var app = express();
var serv = require('http').Server(app);
var net = require('net');
var path = require('path');
var port = 3000;

app.use('/../public/', express.static(path.join(__dirname + '/../public/')));

app.get('/', function(req,res){
res.sendFile(__dirname + '/../public/index.html');

serv.listen(3000, function(){
console.log('port ' + port + ' is started to being listened')

var io = require('socket.io')(serv,{});

it returns forbidden error. How can I reach a file in another subfile?

OK, I solved it, thanks to @Michael Troger. After your answer, I understood what other people wanted to say about similar issues on other posts. I am a game developer doesn't know much about web programming. So trick is;

as @Michael Troger said, '/' denotes main folder in localhost so

app.use(express.static(__dirname + '/../'));

app.get(__dirname, function(req,res){
res.sendFile('public/index.html', {root:__dirname});

fixes the problem.


doesn't really make sense. You can't listen for request URL's in the hierarchy outside of the root.

Remember that app.use('/' equals a request URL like http://localhost:3000. So where should '/../public' point to?

If you write app.use('/public' it will listen for requests on http://localhost:3000/public

So probably what you wanted is:

app.use(express.static(__dirname + '/../public'));

in order to search the static files in a folder structure like:


where you could access static files like http://localhost:3000/styles.css

You can also remove:

app.get('/', function(req,res){
    res.sendFile(__dirname + '/../public/index.html');

static files like HTML are already served by the controller mentioned above. You can access your index.html by calling http://localhost:3000