Can't link between folders in express.js

I'm new to node.js and express.js, so I feel like I might have syntax problems, I have the following node.js code:

var express = require('express');
var path = require('path');
var app = express();

app.set('port', process.env.PORT);

app.use(express.static(path.join(__dirname, 'static')));
app.get('/', function(req,res){
   res.render("/public/index")
});
app.get('/secure', function(req,res){
  res.render("/secure/index")
});
var server = app.listen(app.get('port'), function(){
  var port = server.address().port;

});

      

This allows me to access the secure page for sure, however the page shows "Internal Server Error" when I try to access the public page, why is that? My file structure

static
-public
--index.html
-secure
--index.html

      

If I convert the public index.html to static then it works great, but I would rather have the above file structure, is there anyway I can do this? Thank you.

+3


source to share


2 answers


When you make a request in yourdomain:yourport/

, express will process the request in app.get("/", ..)

and find that the handler is res.render

. So it will return an error as this function needs to look over the engine to define on top app.get()

.

Since the files that are files are static html files, you can uninstall the middleware app.get()

. You already have static processing middleware app.use(express.static(path.join(__dirname, 'static')));



var express = require('express');
var path = require('path');
var app = express();

app.set('port', process.env.PORT);

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

var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
});

      

So, to get a page public

, just make a request to yourdomain:yourport/public

. Meanwhile, the protected page is available in yourdomain:yourport/secure

.

0


source


I had to:

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

app.get('/', function(req,res){
   res.render("public/index")
});

      



to make it work with your directory structure.

0


source







All Articles