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");
});
Related
res.redirect function is used to redirect the user to another page by clicking a button. But the function's not working. Please find the code below.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/failure", function (req, res) {
res.redirect("/");
});
app.post("/success", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function () {
console.log("The server is running at port 3000");
});
Try moving
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
below your other routes and try calling again
Try changing app.post to app.get:
app.get("/success", function(req, res) {
res.redirect("/");
});
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);
Lets say I want to have 2 different instances in "subfolders" in the url. In app js I have it defined like this:
var routes = require('./routes/index');
app.use('/myapp1', routes);
app.use('/myapp2', routes);
The inner routing would be the same.
But still in the router I want to "get" the path defined in the app.use - eg.: myapp1, myapp2
How do I get this in the router?
From routes/index.js:
router.use(/\/.*/, function (req, res, next) {
// want to see "myapp1/myapp2" without the *sub* path defined in this particular router eg.: /products /user etc.
next();
});
You might want to use the req.baseUrl property.
Example:
routes.get('/1', function(req, res) {
res.send([
req.baseUrl,
req.path,
req.baseUrl + req.path,
].join('\n'));
});
app.use('/api', routes);
Making an HTTP request to /api/1 would print:
/api
/1
/api/1
var express = require('express');
var app = express();
var router = express.Router();
app.use(function(req, res, next) {
req.appInstance = (req.url.indexOf('/app2/') == 0) ? 2 : 1;
next();
});
app.get('/', function(req, res, next) {
res.redirect('/app1/user');
});
router.get('/user', function(req, res, next) {
res.send(req.url +' on app' + req.appInstance);
});
app.use('/app1', router);
app.use('/app2', router);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
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);
});
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