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);
});
Related
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 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);
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);
});
I am using express to serve a single page webapp, and as a REST endpoint for said app. Everything works fine for the static page serving, but after 5 posts the server becomes unresponsive. I have seen a lot of other posts with this problem but they all say to just make sure to call res.send() or res.end() which i do in every call somewhere, regardless of how the logic branches. The app.js code is below.
/**
* Module dependencies.
*/
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
var auth = require("./controllers/authentication.js");
http.globalAgent.maxSockets = 100;
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
app.get('/public/*', function(req, res) {
res.sendfile('.'+req.url);
});
app.post('/auth/login', function(req, res, next) {
auth.login(req, res, next);
});
app.post('/auth/logout', function(req, res, next) {
auth.logout(req, res, next);
});
app.post('/auth/verify', function(req, res, next) {
auth.verify(req, res, next, function(req, res, next) {
res.conentType = 'json';
res.send(200, "authorized");
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
and here is the command line output that i get (i tried issuing other requests after, but the server would not process them). I assume that I am somehow not terminating the connection properly, but cant figure out how.
problem was related to not closing mysql connection pool
I want to use express.js with Flatiron's director (router) and Resourceful (ODM) because I need like the benefits of routing tables and clean multi-db schemas with validation.
The reason why I now completly switch to Flatiron is, is because I think it needs some more time and there is not much doc material.
However, that is the current way I use director in express:
var express = require('express')
, director = require('director');
function hello(){
console.log('Success');
}
var router = new director.http.Router({
'/': {
get: hello
}
});
Unfortunatly this doesn't work and gives me just a "Cannot GET /"
So what's to do?
var express = require('express')
, director = require('director')
, http = require('http');
var app = express();
var hello = function () {
this.res.send(200, 'Hello World!');
};
var router = new director.http.Router({
'/': {
get: hello
}
});
var middleware = function (req, res, next) {
router.dispatch(req, res, function (err) {
if (err == undefined || err) next();
});
};
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.bodyParser());
app.use(middleware);
app.use(express.static(__dirname + '/public'));
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
There is a sample app using express, resourceful and director here.
If you have more doubts, you can ask them in our IRC room #nodejitsu on freenode.
First, in order to use director you need to wrap it up as a middleware and pass it to express, like so:
app.use(function (req, res, next) {
router.dispatch(req, res, function (err) {
if (err) {
// handle errors however you like. This one is probably not important.
}
next();
});
};
Aside from that: You don't need director to use resourceful, and express has its own router (so you may not even need/want director).