Linking HTML form action to node js function - javascript

I'm trying to execute a function in node.js when a users enters information on a form in html. I keep getting 404 not found and am not sure where to go. I'm sure there are other questions similar to this but have searched around and can't find anything.
HTML Code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<link rel = "stylesheet"
type = "text/css"
href = "style.css" />
<form action="/zipCheck" method="post" accept-charset="utf-8">
<input placeholder="Enter your zip code to start" class = "zipInput">
</form>
</html>
Node.js code:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
console.log("hello");
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
app.use(logger('short'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.post('/zipCheck', function(req, res){
console.log("GOOD");
});
// 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;

The order of middleware loading is important: middleware functions that are loaded first are also executed first.
You added the /zipCheck route after the error handler, your requests will never reach this handler and
your app will not print GOOD.
You need to reorder your routes handler, also add a slash before zipCheck
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.post('/zipCheck', function(req, res){
console.log("GOOD");
});
// error handler
app.use(function(err, req, res, next) {
})

Related

req.body throws an empty {}

I am using body-parser but it's not working and I don't know what the problem is.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
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')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// 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;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', redirection, function(req, res, next) {
res.redirect('index', {title: 'Home'});
});
router.get('/country', function(req, res, next) {
// CountryName
res.render('country',
{
title: 'Home',
mainJS: 'main.js',
//country: req.body.countries
});
console.log(req.body)
});
function redirection(req, res){
if (req.url == '/'){
res.redirect('/country');
}
}
module.exports = router;
In this code it throws {}
What is the problem?
Your server only receives a request body in POST (or PUT or PATCH) operations, not in GET operations. You don't have router.post() in your sample code, so it seems you are not handling POSTs. Therefore, no req.body.
You can find your https://example.com/?query=parameters&query2=parameters at req.params.query and req.params.query2.
You can't use the location bar of a browser to do a POST: they from a form posts or xhr / fetch operations.

Why router in Express/node.js return 404

I just generated Express app and added custom route (/configuration). But if I try to open http://localhost:3000/configuration, server returns 404 Not Found error. I checked the code and don't understand where is error.
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 index = require('./routes/index');
var config_page = require('./routes/configuration');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
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('/configuration', config_page);
// 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.render('error');
});
module.exports = app;
routes/configuration.js (routes/index.js is similar)
var express = require('express');
var router = express.Router();
/* GET configuration page. */
router.get('/configuration', function(req, res, next) {
res.render('configuration', { title: 'My App | Configuration' });
});
module.exports = router;
This code is the problem
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Also the current Url which is generated by your application is http://localhost:3000/configuration/configuration. If you make a query on this then it will work. Now if you wan to use it with http://localhost:3000/configuration. then you need to remove on path from anywhere. May be you can change in main file like this
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('/',config_page); //-----------> this is the line you need to change
How can it be used for error handling. Remove it and add this code to catch any error in application.
process.on('uncaughtException', function (err) {
// This should not happen
logger.error("Pheew ....! Something unexpected happened. This should be handled more gracefully. I am sorry. The culprit is: ", err);
});

Consecutive Post request node JS

I wanted to know that
Can i do consecutive post requests in separate route file and with each post request redirect to a different ejs page.
This is my file structure
routes:-index.js
-users.js
-users1.js
views:-index.ejs
-users.ejs
-users1.ejs
this is 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 users1 = require('./routes/users1');
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(path.join(__dirname, 'public', 'favicon.ico')));
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);
app.use('/users1', users1);
// 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 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;
this is my index.js
`var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/users', function(req, res, next) {
res.redirect('/users');
});
module.exports = router;`
This is my index.ejs:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form action="/users" method="post">
<input type="submit" value="post">
</form>
</body>
</html>
this is my users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('users');
});
router.post('/users1', function(req, res, next) {
res.redirect('/users1');
});
module.exports = router;
this is my users.ejs
<html>
<head>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form action="/users1" method="post">
<input type="submit" value="post">
</form>
</body>
</html>
this is my users1.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('users1');
});
module.exports = router;
this is my users1.ejs
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>hello</h1>
</body>
</html>
the post request from index.ejs to users.ejs is working fine and it is redirecting to users.ejs
but the request from users.ejs to users1.ejs is not working .
and it shows 404 not found
this is the entire console.log output
> hostelSystem#0.0.0 start /home/ritwik/hostelSystem
> node ./bin/www
POST /users 302 43.621 ms - 56
GET /users 200 10.041 ms - 205
GET /stylesheets/style.css 304 2.742 ms - -
POST /users1 404 16.965 ms - 946
looks like in your users1 router you are using the router.get you probably want to use router.post because you are requesting domain.com/users1 it goes directly to this router only, and i only notice now that you dont need the forwarding because when you call domain.com/users it goes directly to the users router
router.post('/', function(req, res, next) {
res.render('users1');
});
module.exports = router;

Express Error: TypeError: Router.use() requires middleware function but got a Object

I am creating an upload/download app, i don't know why its only my app.js file is having this problem. I searched all other answers on the internet but still it did not solve the problem.
here is the code below:
var express = require('express');
var path = require('path'); // add path to set and get
var fs = require('fs'); // add filesystem
var connect = require('connect');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var connect = require('connect');
var http = require('http');
var routes = require('./routes/index');
var users = require('./routes/users');
//var upload = require('./routes/upload');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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(express.static('public'));
app.use(express.static('files'));
app.use('/', routes);
app.use('/users', users);
//app.use('/upload',upload);
// 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 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;
Thanks for your help.
check in your all files
make sure you don't miss export it
module.exports = router;
Router.use() at all times requires a Middleware function as an argument. Assuming your route to download some files from your server, it should Look similar to this.
var Router = express.Router();
function downloadFiles(request,response) {
// some code to dowload files
}
// The above function which takes request and response
// should be passed to Router.use()
Router.use(downloadFiles);
When you that error it means that what you passed to Router.use() is not a middleware function like downloadFiles.

Getting response after posting to mongodb

I tried testing my code written to post data to mongodb via postman using x-www-formurlencoded but I keep getting this error:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
at Layer.app.use.res.render.message [as handle] (c:\Users\Tomix\Documents\Source\Tomix\app.js:39:15)
at trim_prefix (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:226:17)
at c (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:198:9)
at Function.proto.process_params (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:251:12)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:189:19)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:166:38)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:150:14)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:166:38)
at Function.proto.handle (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:234:5)
at Layer.router (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:23:12)</pre>
</body>
<!--Live reload script -->
<script type="text/javascript" src="http://localhost:35729/livereload.js"></script>
</html>
So what am trying to do is to create an e-commerce website with mean stack,so am trying to structure the app files and folder to reflect the server side and the client side.
The code here is to save data to database (mongodb), but from the error message I was able to deduce is that at the point it ought to return response in json format it throws the error message.
exports.create = function(req, res) {
console.log('I got called', req.body);
var product = new Product(req.body);
product.save(function(err) {
if (err) {
return res.send(400, {
message: err
});
} else {
res.json(product);
}
});
};
My app.js file
'use strict';
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var routes = require('./routes/index');
var users = require('./routes/users');
/*connecting the to database*/
require('./config/db');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
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
});
next();
});
}
// 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: {}
});
next();
});
//Routes
require('./app/routes/product.server.routes.js')(app);
exports = module.exports = app;
Please am stuck have search online for possible solution, some of the suggestion I got was I need to add method-override to my express configuration.
I think that you missed a part of the equation:
Post/Info -> Connector/Driver -> Mongodb/Database
Yo can not post JSON to mongo via Postma. You'll need to find a mongodb solution for javascript to play with it. You can try it with Node.js for example. Here I give you a list of all the language possibilities to connect to mongo.
http://docs.mongodb.org/ecosystem/drivers/
Hope it helps!

Categories