DanT29
DanT29

Reputation: 3229

ExpressJS not serving static templates using app.use

I have form that I am trying to serve as a static page using ExpressJS via app.use, but I'm getting an error.

const express = require('express');
var app = express();
app.use(express.static(__dirname + 'public'));
app.listen(3000);

This is my folder structure

App Name
-node_modules/
-public/
       login.html
-package-lock.json
-package.json
-server.js

My error is Cannot GET /login when I go to localhost:3000/login. What can I do to fix this? It seems to work when I use template rendering using handlebars.

EDIT: I'm also running on windows 10 if that helps. putting app.use(express.static(__dirname + '**/public**')); isn't solving the issue either.

Solutions:

1.

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

 app.use(express.static(path.join(__dirname, 'public'),{
    extensions: ['html']}
  ));

 app.listen(3000);

2.

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

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

app.listen(3000)

3.

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

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

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

}); 

app.listen(3000)

Upvotes: 1

Views: 276

Answers (2)

Andrei
Andrei

Reputation: 1216

from the official document

as shown from the console.log(__dirname + 'public') you got C:\Users\Daniel\Desktop\web\drone-apppublic which is the incorrect directory.

the safest way to do this is by using the path lib provided by node.js app.use(express.static(path.join(__dirname, 'public')));

C:\Users\Daniel\Desktop\web\drone-app\public\

lastly because it's serving static files you need to include the file extension I just tested it and it only works with localhost:3000/login.html if you want to remove the extension for html files you can add the rule to the static function as such

app.use(express.static(path.join(__dirname, 'public'),{ extensions: ['html']} ));

you can find the rest of the available function properties here

Upvotes: 1

C.Unbay
C.Unbay

Reputation: 2826

If it says CANNOT GET LOGIN And tells you that it can not get to login directory, but doesn't throw an error, that means you haven't specified login dir in your server.js file

please add this piece of code before trying to go to the link again.

app.get('/doesItWork', function(req,res){
   res.send('it works!!');
})

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

Upvotes: 1

Related Questions