express.static doesn't point to the right path - node.js

I get a problem every time I try to reach /about
This code works and all is fine
var express = require('express');
var path = require('path');
var app = express(); // define our app using express
var port = process.env.PORT || 3000; // set our port
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'public')+'/index.html');
})
.get('/about', function(req, res) {
console.log(__dirname);
res.sendFile(path.join(__dirname, 'public')+'/about.html');
})
.get('/signIn', function(req, res) {
res.sendFile(path.join(__dirname, 'public')+'/signIn.html');
});
app.listen(port);
console.log('Magic happens on port ' + port);
but when I try to place the public folder in express.static I get an error
"Error: ENOENT: no such file or directory, stat 'C:\about.html'
at Error (native)"
var port = process.env.PORT || 3000; // set our port
app.use(express.static(path.join(__dirname, 'public')));
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res) {
res.sendFile('/index.html');
})
.get('/about', function(req, res) {
console.log(__dirname);
res.sendFile('/about.html');
})
.get('/signIn', function(req, res) {
res.sendFile('/signIn.html');
});
app.listen(port);
console.log('Magic happens on port ' + port);

Related

Remove filename from URL with Express

When I host my front-end on Nodejs, I use app.use(express.static(path.join(__dirname, "public")));. However, this makes me put the name of the HTML file at the end of the URL; for example, localhost:3000/index.html.
How would I make it show the front-end at the base URL, in this case, "localhost:3000/". I have attached a part of my Nodejs code. I would appreciate any help and thank you in advance.
var path = require('path');
var express = require('express');
const app = express();
const port = process.env.PORT || '3000';
app.use(express.json());
app.use((req, res, next) => {
console.log(req.path);
next();
});
app.use(express.static(path.join(__dirname, "public")));
app.listen(port, () => console.log("Server is ready"));
You can use a route path and sendFile method:
app.get("/", function(req,res) {
res.sendFile("index.html", {root: path.join(__dirname, "public")})
})
More details here
This is how you would do.
//for static files like css and html
app.use('/static', express.static(path.resolve(__dirname, path to css and js)));
app.get('/*', (req, res)=>{
res.sendFile(path.join(__dirname, 'path to your html file'))
})

Set new.html as the base file

I would like to set new.html as the base file for the server, but it keeps defaulting to index.html
My code is below...
const express = require('express');
const app = express();
// Set '/public' as the static folder.
app.use(express.static(__dirname + '/public'));
// Set index.html as the base file
app.get("/", function(req, res) {
res.sendFile(__dirname + '/new.html');
});
var server = app.listen(4000, function() {
console.log('Listening to requests on port 4000');
});
You can specify the index file to use as an option to express.static():
const express = require('express');
const app = express();
// Set '/public' as the static folder.
app.use(express.static(__dirname + '/public', {
index: 'new.html'
}));
const server = app.listen(4000, function() {
console.log('Listening to requests on port 4000');
});
Then, you no longer need the / route.
Alternatively, you could specify your / route before your static directory:
const express = require('express');
const app = express();
// Set new.html as the base file
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/new.html');
});
// Set '/public' as the static folder.
app.use(express.static(__dirname + '/public'));
const server = app.listen(4000, function() {
console.log('Listening to requests on port 4000');
});
Note: the file path should be /public/new.html rather than /new.html.

Why sendFile is ignoring parameters provided for it?

I am using the following simple server.js to randomly point to two different HTML files on the server. However, it is automatically redirecting to index.html (not even in the parameters any more) and not the index1.html or index2.html.
I am not sure what I am missing here
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use(express.static('public'))
app.get('/', function(req, res) {
if((Math.floor(Math.random() * 2) + 1)>1)
{
res.sendFile(__dirname + "/public/index1.html");
}
res.sendFile(__dirname + "/public/index2.html");
});
/*--------------------Routing Over----------------------------*/
app.listen(port, function () {
console.log(`Server listening on port ${port}!`);
});
As i executed your code it was looking fine to me and changing file index1.html and index2.html randomly.
If you want to change with route as well then i'll suggest below scenerio :
var express = require('express');
var app = express();
var port = process.env.PORT || 3002;
app.use(express.static('public'))
app.get('/index1.html', function(req, res) {
res.sendFile(__dirname + "/public/index1.html");
});
app.get('/index2.html', function(req, res) {
res.sendFile(__dirname + "/public/index2.html");
});
app.get('/', function(req, res) {
if((Math.floor(Math.random() * 2) + 1)>1)
{
console.log("index1");
res.redirect("/index1.html");
}
console.log("index2");
res.redirect("/index2.html");
});
app.listen(3002);
To send either index1.html or index2.html you have to use the else condition. Further, I have used the path module to create the path, which is the best practice.
var express = require('express');
var app = express();
var path = require("path");
var port = process.env.PORT || 3000;
app.get('/', function (req, res) {
if ((Math.floor(Math.random() * 2) + 1) > 1) {
res.sendFile(path.join(__dirname, "/public/index1.html"));
} else {
res.sendFile(path.join(__dirname, "/public/index2.html"));
}
});
/*--------------------Routing Over----------------------------*/
app.listen(port, function () {
console.log(`Server listening on port ${port}!`);
});

routing node.js and express

I'm having a problem routing in express 4. I was following the example, but it isn't loading. I'm just getting a spinning wheel.
How do you do routing in express version 4?
app.js:
var express = require('express');
var http = require('http');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var port = (process.env.PORT || process.env.VCAP_APP_PORT || 5000);
app.use('/birds', require('./controller/bird'));
http.createServer(function (req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World!\n');
}).listen(port);
console.log('Server running at http://127.0.0.1:'+port);
bird.js:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
You're not calling the app.listen() function. Instead of the http.createServer one, you should invoke the Express function.
Please, take a look at a basic example.
Relevant code:
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Edit: as slebetman wrote in the comment, the more general way for it is:
http.createServer(app).listen(port, function(){
console.log('now listening on port ' + port);
});

Can't intercept 404 with express node js

This is my code:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile(__dirname + '/public/error.html');
});
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});
When I access the url http://localhost:3000/xyz, which does not exist, I get the standard page saying Cannot GET /xyz, instead of my custom error page. Why?
The function signature you're using (err, req, res, next) is for errors. E.g. a middleware calls next(new Error('failed')). What you need is a regular middleware which simply happens to be the last one that is executed, which means you interpret it as 404 (see answer below).
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile(__dirname + '/public/error.html');
});
//------------------
app.use(function(req, res, next) {
res.status(404);
res.sendFile(__dirname + '/public/error.html');
});
//------------------
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});
Node usually starts matching endpoints from top to bottom.
So first write down all the endpoints of your app, then write an endpoint like below at the end which will be executed when none of your defined endpoints match.
app.get('/path1', handler1);
app.get('/path2', handler2);
app.get('/path3', handler3);
app.get('/*',function (req, res) {
//This block will executed when user tries to access endpoint other than /path1,/path2,/path3
// Handle error here
})
Your code should look like this :
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.get('/*',function (req, res) { //If any of your defined endpoints doesn't match, this block will be executed.
res.status(404);
res.sendFile(__dirname + '/public/error.html');
});
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});

Resources