Why sendFile is ignoring parameters provided for it? - node.js

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

Related

React router not working when navigating using url

I am getting an error Cannot GET /'page' when trying to navigate using url to a path in React Router. Navigating from application works perfectly fine. Here is my server.js:
const express = require('express');
const app = express();
const port = process.env.PORT || 3001;
const path = require('path');
app.use(express.static('build'));
app.listen(port, () => {
console.log('Server is up on port: ' + port);
})
I've tried adding this code snippet to my server but it didn't work:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './public/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})

How to test Socket.io and Express on a DOMAIN

I am trying to run Node.js on a domain that I do NOT own (basically a snadbox), I figured the problem is that socket.io and express are not running. The domain I have access to upload files to is https://'Domain'.com/MyID (domain is in quotes so it doesn't make a link here)
The code shown is what runs perfectly on localhost NOT ON A DOMAIN, this is my first experience with node thus I do not know what to do after weeks of videos that only show it running on localhost.
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
So I found this
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
And I'm wandering if I can set hostname to a domain directory (directory being my access to edit /MyID)
Before edit:
I tried changing the requirements in the code above but that did absolutely nothing
var express = require('express');
var app = express();
var serv = require('https://'example'.com/MyID').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
Please help me I do not know what to do.

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

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

Express Node JS

Following is my code as follows:
var express = require('express');
var app = express();
var router = express.Router();
app.route('/')
.get(function(req, res) {
res.send('Hello World!');
});
app.route('/user')
.get(function (req, res) {
res.send('Hello' + req.params.id);
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
It runs fine with http://localhost:8000/ but with http://localhost:8000/user?id=D it gives following error: Cannot GET /user?id=D.
WHat is wrong in my code? Please help.
Thanks.
This route syntax:
'/user/:id'
matches a URL like this:
http://localhost:8000/user/4095
If you use a URL like this:
http://localhost:8000/user?id=D
then, you will need to use a "/user" route and read the query parameter for the id value from req.query.id as described here.
In addition, your don't need the app.route() as it's just an extra level of complication for things you are not doing here. I'd suggest this simplification which I have tested and works:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Hello World!');
});
app.get('/user', function (req, res) {
res.send('Hello: ' + req.query.id);
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Resources