500 Error with Express Routing - javascript

I've just started learning Node/Express and am currently trying to add a new page and route for it. I'm currently getting a 500 error.
My code is as follows (I've deleted the bits that aren't relevant):
app.js
var express = require('express');
var index = require('./routes/index');
var upload = require('./routes/upload');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/upload', upload);
app.use(express.static('public'));
upload.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('upload', { title: 'Upload Image' });
});
module.exports = router;
All the routing is correct. I tried replacing the code in upload.js with the code in index.js (that comes with express-generator), and that worked.

Related

How to route the form action to a specific file by using express router

I'm using express.router and ejs template. I want the logic of one of my form with a POST method will be handled not in the app file (the main file of the application) but in some other file with the name 'user.js' using router.post. It returns 404 since it's trying to find the logic on the main file instead on the users.js file.
How can I route the post logic to be handled in the user.js file?
app.js file
const express = require('express');
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
var router = express.Router();
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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.render('error');
});
module.exports = app;
users file (routes/users.js)
var express = require('express');
var app = require('../app')
const axios = require('axios');
var bodyParser = require('body-parser');
const {User} = require('../models/userModel')
const mongoose = require('mongoose');
const mongodb = require('mongodb');
const router = express.Router();
router.get('/', function(req, res, next) {
res.render("user");
});
router.post('/userSearch', (req, res) => {
res.send(req.body.myUser);
})
module.exports = router;
user file (views/user.ejs)
<h1>Welcome to users page</h1>
<form action="/userSearch" method="POST">
Search user:<input type ="search" name="myUser"></br>
<input type = "submit">
</form>
There are few unnecessary declarations on your files but the main reason your are not reaching the router path is because you are POSTing to a NOT declared route:
<form action="/userSearch" method="POST">
should be:
<form action="/users/userSearch" method="POST">
EXTRA
Few fixes for your files:
app.js
var router = express.Router(); //not needed here
users file (routes/users.js)
var app = require('../app') //not needed here

Cannot GET /api/tasks

Every time I call: http://localhost:3000/api/tasks am getting a Cannot GET /api/tasks
My server.js
var express = require('express');
var path = require('path');
var BodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'client')));
// Body Parser MW
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('api', tasks);
app.listen(port, function(){
console.log('Server started on port '+port);
});
I am still learning the ropes. Thank you in advance
tasks.js
var express = require('express');
var app= express();
var mongojs = require('mongojs')
var db = mongojs('mongodb://<user>.:<****>#ds125365.mlab.com:25365/mytasklist_wafalme', ['tasks'])
// Get All Tasks
app.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
// Get Single Tasks
app.get('/tasks/:id', function(req, res, next){
db.tasks.findOne({_id: mangojs.ObjectId(req.params.id)}, function(err, task){
if(err){
res.send(err);
}
res.json(task);
});
});
module.exports = app;
I have attached the task.js file that runs in the routes folder with the index.js
Use an absolute route to define the API routing context:
app.use('/', index);
app.use('/api', tasks);
Always include a forward slash (/) at the beginning of your routes.

Routing an Invalid Request to a 404 Error Page

I'm trying to build a server that user will be able to enter these valid paths:
localhost:9090/admin
localhost:9090/project1
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path localhost:9090/404.html:
How do I do it?
this is my code:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
route.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
res.render('c:/monex/myprojects/' + name +'/index');
});
app.use(function(req, res, next){
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
});
module.exports = router;
Expressjs has a pretty cool way of handling errors and routing them.
1/ To Confirm if project exists
We use the filesystem module to confirm if it exists, using the access API, you can read more on the module at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html
var fs = require('fs') // We'll need to ask the filesystem if it exists
var projectname = 'myfolder';
// Excerpt from your code, but Modified
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
fs.access(name, fs.constants.F_OK, function(err) {
if(!err) { // directory exists
res.render('c:/monex/myprojects/' + name + '/index');
return;
}
// Directory does not exist
next({statusCode: 404});
})
});
2/ To route the error properly
From the above code, we said anytime directory does not exist in nodejs, call next with an error object, i.e next(err), the difference between next() and next(err) is that there are two types of middlewares in expressjs, the first is:
app.use("/", function(req, res, next) {})
while the second is
app.use("/", function(err, req, res, next) {})
The difference between the two is that, the first one is a normal middleware that routes requests through. But the second is called a error handling middleware. Anytime that next function is called with an argument, express jumps to route it through error handling middlewares from there on. So, to solve your problem.
You will want to solve this at the app level so that all across all routers, you can have 404 pages delivered.
In app.js
function Error404(err, req, res, next) {
if(err.statusCode === "404") {
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
}
// YOu can setup other handlers
if(err.statusCode === "504") {}
}
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(Error404);
REFERENCES
http://expressjs.com/en/guide/error-handling.html
https://www.safaribooksonline.com/blog/2014/03/12/error-handling-express-js-applications/
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
Try changing the signature of your 404 handler function
Express will use it as an error handler of just add change function parameters to: (err, req, res, next)
I also got it fixed by adding this to my app.js
app.use(function (err, req, res, next) {
res.render('c:/monex/505.html', { status: 500, url: req.url });
})
making it look like this
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(function (err, req, res, next) {
res.render('c:/monex/404.html', { status: 404, url: req.url });
})
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})

Node Express.js 4 Route Not working, Getting 404

I've been trying to debug my route in my express app. The request is undefined but not sure why.
I'm using Express 4.0 but running it Express 3.0 style (no bin/www).
server.js
var app = require('./app')
var port = process.env.PORT || 3000;
app.set('port', port);
app.listen(app.get('port', function(){
console.log('Express web server is listening on port ' + app.get('port'));
}));
app.js
var express = require('express'),
path = require('path'),
routes = require('./routes/index'),
app = express();
app.use('/', routes);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app;
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
When I run debug on my app in webstorm, the page throws a 404 page not found. When I looked at the debug, here's the problem, the http request is undefined:
Make sure your app.listen... looks as follows
app.listen(app.get('port'), function() {
console.log('Express web server is listening on port ' + app.get('port'));
});

Node.js server has no response

I'm using NODE.js and Express (express-generator) to create a website. I had this working just fine yesterday afternoon, but I guess I changed something and it doesn't work now. My firewall is turned off.
I get the following in my console.
C:\website>node bin/www
Listening on 8080
Get / - - ms - -
Get / - - ms - -
Get / - - ms - -
Each of those Get / - - ms - - happens each time I try to go to 127.0.0.1:8080
Here is my bin/www file:
#!/usr/bin/env node
var debug = require('debug')('test');
var app = require('../app');
app.set('port', process.env.PORT || 8080);
var server = app.listen(app.get('port'), function() {
console.log("Listening on " + server.address().port);
debug('Express server listening on port ' + server.address().port);
});
And my app.js:
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(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('/', routes);
app.use('/users', users);
// 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
// production error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err);
});
module.exports = app;
This behavior might be the result of incorrectly defined routes. Your routes should follow this pattern:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;

Categories

Resources