Set new.html as the base file - node.js

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.

Related

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}!`);
});

Angularjs, express and nodejs bug with view rendering

I'm new in Angularjs and i'm trying to create a basic one page app using ngRoute. But i have a problem. I wan't my user to get the index.html file everytime. But if the url is /page1 my server is returning the page1 so index.html isn't loading. I tryed to fix it by doing like that :
Angular file :
test.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : '/page1',
controller : 'trapController'
})
.when('/test', {
templateUrl : '/page2',
controller : 'trapController'
});
$locationProvider.html5Mode(true);
});
Node.js file :
require('dotenv').load();
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const bodyParser = require('body-parser');
const path = require('path');
const apirouter = require('./apirouter');
const viewrouter = require('./viewrouter');
app.use('/api', apirouter);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.engine('html', require('ejs').renderFile);
app.use('/*', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
// START THE SERVER
// =============================================================================
app.listen(port, () => {
console.log('Server running on port ' + port);
});
But this way nothing is working.. It seems like every call is asking to the server and not looking into the public folder. So when i call for a .js file it load me a new index.html file... I don't know how to do.. Can you help me ? :)
I was apparently doing wrong with :
Better use this :
app.use('/', express.static(__dirname + '/public'));
Than this :
app.use(express.static(path.join(__dirname, 'public')));

How do I return an index.html file from express using the package 'express-https-redirect'

I have the following code which is defaulting to use HTTPS, I'm just unclear how to send an index.html file back
var express = require('express'),
path = require('path'),
fs = require('fs'),
app = express(),
staticRoot = __dirname + '/',
httpsRedirect = require('express-https-redirect');
app.set('port', (process.env.PORT || 3001));
app.use('/', httpsRedirect())
app.listen(app.get('port'), function () {
console.log('app running on port', app.get('port'));
});
Any help is greatly appreciated
You can send the html file usually asfollows
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
Note: express-https-redirect middleware redirects non-secure access to HTTPS Only.

express.static doesn't point to the right path

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);

socketio and nodejs, error 404 /socket.io/socket.io.js

I'm getting this error "NetworkError: 404 Not Found - http://localhost:3000/socket.io/socket.io.js" and I don't know how can I fix it. I have tried changing the port, adding the link with the port ... and I have no idea.
My app.js :
var express = require('express')
, http = require('http')
, stylus = require('stylus')
, nib = require('nib')
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib());
}
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
))
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.render('index',
{ title : 'Home' }
)
})
app.listen(3000)
note: The console said it's ok ( info - socket.io started )
Anyway I have tried this
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
but doesn't print the port, say me undefined
You are creating an express HTTP server as well as a standard HTTP server. The app in your example above refers to the Express app which does not have .get('port'); method, try using server.listen. For example:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);

Resources