Express.js Continues to Show 'Not Found' After Removing Default Code - javascript

I thought this was a caching issue, but after three complete removals of all code on my server, I'm still encountering the same issue:
Express Generator comes with the default error handling in the app.js file:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.redirect('/');
});
I have since replaced that code with my own catch all route, using app.all:
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler (catch-all)
app.all('*', function(req, res) {
res.render('index.html');
});
Keep in mind that the render statement works. I'm using a single page application and I need it to redirect back to the index.html file.
This actually works locally, but does not work on my server. The server is a Node.js server.
The default message for the 404 error is "Not Found". No matter how many times I remove this code and the 404 error message, I continue to see "Not Found" (Express.js style) on my browser, instead of a redirect to my home page.

Coming back to this question, the issue was with my web host. The server uses Phusion Passenger and the app.js on the Node.js server needed to be restarted.
I needed to create a file in the root of the server called restart.txt inside of a folder named 'tmp':
nano tmp/restart.txt
Afterwards, if I wanted to manually restart the server, I would have to run the following command:
touch tmp/restart.txt
Which would restart the app.js file.

Related

TypeError: Router.use() requires a middleware function but got a Object nodejs [duplicate]

I am getting this error when I run npm start to run my express app.
TypeError: Router.use() requires middleware function but got a Object
my app.js code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
my index.js code
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET Hello World page. */
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' })
});
module.exports = router;
I am quirte new to using Node and express. I cant see where I have gone wrong. Can anybody see what my problem is?
I found the answer in the comments from Kop4lyf:
check your users.js. It should also be exporting the router like
index.js, if you can try that.
However, this question was my top search result when I ran into this issue, so I am promoting to an answer.
The error is caused because one of your route modules is not being exported - meaning Express does not have access to it when it tries to identify all of your routes.
You can fix this by adding module.exports = router; to the end of each of your route files.
Example:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
//Do whatever...
});
module.exports = router;
More information about module.exports can be found on this question or the offcial Node.js documentation.
I have fixed this by adding which i am using somewhere. So please check your all exports.
module.exports = router;
If you use in routes
exports default router
Your solution can be
module.exports = router
I had the same error , fixed it by replacing app.use('view engine', 'ejs') with app.set('view engine', 'ejs').
For reference I used this webpage Migrating from 3.x to 4.x
I didn't have to make any changes to either index.js or application.js. For more information on EJS one could refer Using EJS with Express and Express 4.x API
Your index.js file is fine you just have to create users.js and export it.
let express = require('express');
let router = express.Router();
//Login Page - GET REQUEST
router.get('/login',(req,res)=> {
res.send('login page');
})
//Register Page - GET REQUEST
router.get('/register',(req,res)=> {
res.send('register page');
});
module.exports = router;
in every module **export the router** and **keep one handler for the default
path '/'**
// in index.js
const authRoute = require("./routes/authRoute");
app.use("/auth", authRoute);
// in authRoute.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
// code
});
module.exports = router;
This error comes when you forgot to export the module which uses the Router.
Your mentioned code works perfectly with some tweaks.
if your app.js is main/starting point of the app.
it should have
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
instead of
module.exports = app;
(optional)Generally index.js is used for starting point of app. Rename index.js as helloworld.js and change same at require statement
var routes = require('./routes/index');
to
var routes = require('./routes/helloworld');
run this app using the following command
node app.js
If you have checked all the solution than also having this error than check this one
Another cause of having this error is calling a method which is not exist or not not exported.
In my case i am calling login method but i forgot to define them
I was trying to call this method
app.post('/api/login', db.login);
but i had forgot to create login method so i got this error. also try to check spelling mistake may be you might have typed wrong spell
I had the same problem, and then I discovered that I was missing this line in one of my controllers !
return api; //it might be return routerfor your code !
I added this line to my code and it worked fine.
Whew, my problem was that i was doing module.exports = { router } instead of module.exports = router
I found it after lot of struggle! as everything syntactically correct, nothing wrong with code that was written, it was due to the code that was not written yet! This could happen if you have implemented index.js but not yet users.js. However, you have already defined both lines
app.use('/', routes);
app.use('/users', users);
If you are eager to test index.js right away without waiting for users.js to be implemented. That's exactly when it errors out.
if you are still facing this problem and try every solution then just replace router with routes and it worked fine
For anybody using EJS:
In my case I was receiving this error as I used
app.use("view engine","ejs")
instead of
app.get("view engine","ejs")
I fixed it by removing the app.use(/users, users);
I don't need this at the minute so maybe that is why it started breaking.

How setup Node.js error handling?

I have node 7.8.0 and I have read Node.js Best Practice Exception Handling
Still I can't seem to understand error handling in node.js.
For my http I have
server.on('error', () => console.log('Here I should be replacing
the Error console.'));
For 404 I have this code
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res) => {
res.status(err.status);
res.render('error');
});
404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. But it also throws error log to my console and I have no idea where that is coming from and how to stop it.
I would like to use my own error handling and never actually write errors like 404 into the console.
Codes that I tried and don't seem to work.
var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);
I'm not sure how it can render the error view, given that error handlers require 4 arguments while you're passing it only 3. This is how Express can distinguish error handlers from normal route handlers (documented here).
Try this instead:
app.use((err, req, res, next) => {
res.status(err.status);
res.render('error');
});
This is due to expressjs. Expressjs if the env is not equal to the test, the all errors writes to the console.
function logerror(err) {
if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
Also http.Server does not have an event named error.

Not able to trigger main error handler in my node express application

I am using node express (4.15.2), with the default error handler created using express generator function to handle errors.
The code is:
const app = express();
app.set('port', config.enviroment.portNumber);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, config.client.app)));
app.post(config.route.postUploads, uploader.onUpload);
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// this function is never called
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
const server = app.listen(app.get('port'), () => {
const port = server.address().port;
});
In my application I using the following line of code when I need to create an error:
new Error('Some custom error');
But the error handler is never called.
Notes: the error handler is placed after the latest app.use but before app.listen.
Any ideas what could cause this issue and how to fix it?
You need to place the said function at the very bottom of the code because ordering of routes matters (see thisenter link description here). Also, you need to throw your error like so throw new Error('Custom error') in order to trigger the error in your app.
I found a straightforward solution to my problem, basically I had to use
throw new Error('Some custom error');
In general express follows the way of passing errors rather than throwing it, for any errors in the program it could be a good idea to pass the error object to 'next' , and using and error handler so that all the errors passed to next can be handled properly.

Handling 404, 500 and Exceptions in Node.js and Express

I have a node.js + Express + express-handlebars app. I want to redirect the users to 404 page when they go to a page that does not exists and redirect them to a 500 when there is an internal server error or an exception(without stopping the server). In my app.js I have written the middle ware at the end to perform these tasks.
app.get('*', function(req, res, next) {
var err = new Error();
err.status = 404;
next();
});
//Handle 404
app.use(function(err, req, res, next){
res.sendStatus(404);
res.render('404');
return;
});
//Handle 500
app.use(function(err, req, res, next){
res.sendStatus(500);
res.render('500');
});
//send the user to 500 page without shutting down the server
process.on('uncaughtException', function (err) {
console.log('-------------------------- Caught exception: ' + err);
app.use(function(err, req, res, next){
res.render('500');
});
});
However only the code for 404 works. So if I try to go to an url
localhost:8000/fakepage
it successfully redirects me to my 404 page. The 505 does not work. And for the exception handling, the server does keep running but, it does not redirect me to the 500 error page after the console.log
I am confused by so many solutions online where people seem to implement different techniques for this.
Here are some of the resources I looked at
http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html
Correct way to handle 404 and 500 errors in express
How to redirect 404 errors to a page in ExpressJS?
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
The process on uncaughtexception is for the application process - not a per request error handler. Note it takes an err in it's callback and res is not passed. It's a global application exception handler. It's good to have that in the event your global code throws.
One option is you can have all your normal routes (don't see in your example), then a non error handler final * route for 404. That's always the last route meaning it has fallen through all the other routes not finding a match ... thus not found. It's not an exception handling case - you conclusively know the path they are requesting has no match since it has fallen through.
How to redirect 404 errors to a page in ExpressJS?
Then the err route can return 500
http://expressjs.com/en/guide/error-handling.html
The problem is you have two error routes so it always hits the first one which hard codes returning a 404.
The express 4 tool creates this pattern:
var users = require('./routes/users');
// here's the normal routes. Matches in order
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
// note this is after all good routes and is not an error handler
// to get a 404, it has to fall through to this route - no error involved
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers - these take err object.
// these are per request error handlers. They have two so in dev
// you get a full stack trace. In prod, first is never setup
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});

How to post to api from Express.js

I am new to Node/Express and to API's in general. Long story short, I am a front end guy diving into backend and architecture for the first time. The breakdown of my problem is as follows:
App description: A web app that allows users to view medical data records.
Desired feature: Change the state of a json record on page load. When a user opens a record(page), I want to change a json object from UNDIAGNOSED to DIAGNOSED automatically. This needs to be done server side to avoid exposing the api endpoint, which needs to stay hidden for security reasons. Think of it like a 'read/unread' email. Once it has been opened, it changes the state to 'read'
Probelem: ...I am a newb...
//When the server GETs a request to this URL
router.get('/content/:contentid', function(req, res, next) {
// Configure the REST platform call
var platform_options = {
resource: '/content/' + req.params.contentid,
method: 'POST',
json: "diagnosis_state: DIAGNOSED"
};
// Make the call
var platform = ihplatform(_config, req.session, platform_options, callback);
platform.execute();
// Result processing
function callback(error, response, body) {
console.log(response.body);
}
});
I am using a custom HTTP API that was built in-house by another developer. The endpoint for the call is dynamically generated via the re.params.contentid. You will also notice that the call itself is built into the platform.execute function.
There is a bit of copy/pasting going on, as I am trying to modify a working call.
My question is this: How do I make an api POST call to a remote API upon the HTTP request for a certain url via express.js?
Here is what you can do on express.js -
1) write a module for route mappings in a separate js file where all the mappings can be listed. Below is the code snippet of the module file
function mappings(app)
{
var email = require('./routes/emails');// ./routes/emails is js file location exporting UpdateEmail variable which contains function for update
app.put('/email/update', email.UpdateEmail); // mapping url /email/update to exported variable UpdateEmail
}
2) add following statement in app.js file where mapRoutes is a .js file created in step 1
require('./mapRoutes').mappings(app);
3) Below is the sample app.js file
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', false);
res.header('Access-Control-Max-Age', '86400');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
app.options('*', function(req, res) {
res.send(200);
});
require('./mapRoutes').mappings(app);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
4) live website running on above code - kidslaughs.com
I'm not quite sure your question here, because "POSTing from ExpressJS" could mean two different things.
In the most common case, you are making a POST request from a web page. While this might be served or even rendered via Express, the call is originating from the web page. In that case the javascript on the web page is making the post. Common web frameworks for that might be jQuery's $.ajax or Angular's $http. Whatever framework you use, you'll define the data to post, the API endpoint to post to, and what to do with the response.
Another meaning of your question might be that you want your Express app to make a http request from the server side. You will need a package to do so, so that you can make a HTTP programatically. A popular package for this is request.
It's hard to say more without knowing what frameworks you are working with. Keep searching around, you'll figure it out!
I think you're looking for request.js.
var request = require('request');
request.post('/content/' + req.params.contentid').form({json: "diagnosis_state: DIAGNOSED"})

Categories