Express Node JS - 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);
});

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

I can't connect to my node express server on any other device on my network

Here is my server.js code:
var express = require("express");
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, '0.0.0.0', function ()
console.log('Example app listening on port 3000!')
})
Really simple, I just want to see it working on my other devices before I continue.
It works fine obviously on my laptop I'm running it off, but nothing else. Any ideas?
Try removing the '0.0.0.0'
You also have a missing bracket.
Try This:
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Read more:
https://nodejs.org/api/http.html#http_server_listen_path_callback
Try this maybe:
var http = require("http");
var express = require("express");
var service = express();
service.use(service.router);
service.get('/', function (req, res) {
res.send('Hello World!')
});
var server = http.createServer(service);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});

how to use node-ipgeoblock in node js

const express = require('express')
const app = express()
var ipgeoblock = require("node-ipgeoblock")
var server=app.listen(3000, function () {
var host=server.address().address;
var port=server.address().port
console.log('Example app listening on port 3000!',host,port)
});
app.use(ipgeoblock({
geolite2: "./GeoLite2-Country.mmdb",
blockedCountries: [ "FR", "GB", "IN"]
}));
app.get('/', function (req, res) {
res.send('Hello World!')
})
what is wrong in this code, is there any localhost problem ,why am i not able to block countries

NodeJS - create express server on button click event

I'm beginner to Node, I just need to create a express server on a button click event, I did as below but it shouldn't work
script.js
$('#button').click(function(){
$.post('/test');
});
app.js
app.post('/test', function (req, res) {
var express = require('express');
var app = express();
app.get('/test', function (req, res) {
res.send('Hello World');
})
var server = app.listen(3100, function () {
var host = server.address().address
var port = server.address().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);
});

Resources