Cannot POST to a route from and HTML form - javascript

I'm building a nodejs/expressjs application and this is my architecture:
+ routes
- candidate.js
- index.js
+ views
- layout.vash
- register.vash
- server.js
in my server.js file, I put this code to manage routes:
var routes = require('./routes/index');
var candidate = require('./routes/candidate');
app.use('/', routes);
app.use('/candidate', candidate);
in candidate.js, all get requests work fine, but there is a problem in post requests, it can't resolve the path: Cannot POST /caregister
server.js
var routes = require('./routes/index');
var candidate = require('./routes/candidate');
var employer = require('./routes/employer');
var app = express();
app.set('view engine', 'vash');
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('/candidate', candidate);
app.use('/employer', employer);
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('server is listening to ' + app.get('port'));
});
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.render('index');
});
module.exports = router;
routes/candidate.js
var express = require('express');
var router = express.Router();
var Candidate = require("../models/candidate");
router.get('/', function(req, res){
res.render('candidatelogin'); // relative to candidatelogin.vash
});
router.post('/caregister', function(req, res){
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var passwordConf = req.body.passwordConf;
console.log(username + " " + email);
});
module.exports = router;
views/candidatelogin.vash
#html.extend('layout', function(model){
#html.block('body', function(model){
<h1>Jobseeker</h>
<div id="register">
<h3>Create new Account</h3>
<form method="post" action="/caregister">
<input type="text" name="username" placeholder="username"><br/><br/>
<input type="text" name="email" placeholder="email"><br/><br/>
<input type="password" name="password" placeholder="password"><br/><br/>
<input type="password" name="passwordConf" placeholder="password confirmation"><br/><br/>
<input type="submit" value="Register">
</form>
</div>
})
})

When using app.use and including a prefix like candidate that means that you should use this prefix to access this route later on.
So your form in candidatelogin.vash should post to /candidate/caregister url:
<div id="register">
<h3>Create new Account</h3>
<form method="post" action="/candidate/caregister">
<input type="text" name="username" placeholder="username"><br/><br/>
<input type="text" name="email" placeholder="email"><br/><br/>
<input type="password" name="password" placeholder="password"><br/><br/>
<input type="password" name="passwordConf" placeholder="password confirmation"><br/><br/>
<input type="submit" value="Register">
</form>
</div>

Related

<h1><%= text %></h1> reference error text is not defined ejs

So i am making something for fun and i am new to express.js and ejs i made a minecraft server status checker and i want to display the result in <%=text%> from express.js but i am getting this error
ReferenceError: C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\Firebones-Site\views\index.ejs:110
108| <input type="submit" value="Submit" />
109| </form>
>> 110| <h1><%= text %></h1>
111| </div>
112| </body>
113| <script src="js/effect.js"></script>
text is not defined
my index.ejs
<form action="/" method="GET">
<input type="text" name="uwu" required />
<input type="submit" value="Submit" />
</form>
<h1><%= text %></h1>
express (main.js)
//Imports
const express = require("express");
const res = require("express/lib/response");
const app = express();
const port = 3000;
const path = require("path");
const util = require('minecraft-server-util')
app.use(express.static("public"));
app.use("/css", express.static(__dirname + "public/css"));
app.use("/js", express.static(__dirname + "public/js"));
app.use("/img", express.static(__dirname + "public/img"));
app.set("views", "./views");
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
var input = req.query.uwu;
util.status(input)
.then((response) => {
var players = response.players.online;
var maxplayers = response.players.max;
res.render("index", {text: players} )
})
});

Post Request is not working, error showing "cannot post /addstudent/add"

This is the post request I want to send but it is not working. I tried working with it in Postman as well as using forms but the error says "cannot POST /addstudent/add". Below is the code.
This is the JScode: I am using express and using it to post it in MongoDB.
app.post('/addstudent/add', function(req, res){
db.collection('students').insertOne(req.body, function(error, result){
if(error)
throw error;
res.json(result);
console.log("New student Successfully Added!");
})
})
This is the HTML code:
<div class="container-fluid">
<div class="formdiv">
<form action="/addstudent/add" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">Student Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Name" name="Name">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Student Email</label>
<input type="text" class="form-control" id="exampleInputPassword1" placeholder="Email" name="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone Number</label>
<input type="number" class="form-control" id="exampleInputPassword1" placeholder="Phone Number" name="Number">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Age</label>
<input type="number" class="form-control" id="exampleInputPassword1" placeholder="Age" name="Age">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
This is the whole JS code:
var express = require('express');
var bodyParser = require('body-parser');
var mongoDB = require('mongodb').MongoClient;
var hbs = require('hbs');
var app = express();
app.use(express.static(__dirname +'/public'));
app.use( bodyParser.urlencoded());
var url = 'mongodb://localhost:27017';
var db;
mongoDB.connect(url, {useUnifiedTopology: true, useNewUrlParser: true },
function(error, client){
if(error)
throw error;
db = client.db('attainu');
});
app.get('/instructors', function(req, res){
res.render('instructor.hbs');
})
app.get('/students', function(req, res){
res.render('index.hbs');
})
app.post('/addstudent/add', function(req, res){
db.collection('students').insertOne(req.body, function(error, result){
if(error)
throw error;
res.json(result);
console.log("New student Successfully Added!");
})
})
app.listen(3000);
Try this
var express = require('express');
var bodyParser = require('body-parser');
var mongoDB = require('mongodb').MongoClient;
var hbs = require('hbs');
const port = process.env.PORT || 3000;
var app = express();
app.use(express.static(__dirname +'/public'));
//Add this line
app.use( bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json())
var url = 'mongodb://localhost:27017';
var db;
mongoDB.connect(url, {useUnifiedTopology: true, useNewUrlParser: true },
function(error, client){
if(error)
throw error;
db = client.db('attainu');
});
app.get('/instructors', function(req, res){
res.render('instructor.hbs');
})
app.get('/students', function(req, res){
res.render('index.hbs');
});
app.post('/addstudent/add', function(req, res){
db.collection('students').insertOne(req.body, function(error, result){
if(error)
throw error;
res.json(result);
console.log("New student Successfully Added!");
});
});
app.listen(port, () => console.log(`Server is running at ${port}`));
I tried running your same code as given above, every thing works fine. I have made no changes to the code. Data were being posted and successfully saved in database. The result is shown in the following image:

Express.js routers post request returns 404

My express server returns 404 error when i try to send request from html form. However get request works fine. I have separated files for server and routes. I can't make requests in app.js, because there are too many of them (for different pages). I want to make post-insert request to db, but i just can't get any information from my form.
Is there something i missing?
my html form (ejs precisely)
<form action="/add" method="POST">
<input type="text" name="title" placeholder="Event name" />
<input type="text" name="subcategory" placeholder="Category" />
<input type="text" name="date" placeholder="Date" />
<input type="text" name="place" placeholder="Place" />
<input type="text" name="organisator" placeholder="Organisator" />
<textarea name="description" placeholder="Description" onkeyup="adjust_textarea(this)"></textarea>
<input type="submit" value="Add" />
</form>
my App.js file (error on 404 handler)
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//db connection
var mysql = require("mysql");
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'mypassword',
database : 'mydb'
});
res.locals.connection.connect();
next();
});
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('/', require('./routes/index'));
app.use('/events', require('./routes/events'));
//handling errors
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
//server init
var http = require('http');
var server = http.createServer(app);
server.listen(4000);
if(server.listening){
console.log('Server is listening on port 4000');
}
module.exports = app;
my ./routes/events.js file
const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
let query = '*select query*';
res.locals.connection.query(query, function (error, results, fields) {
if (error) throw error;
res.render('index', { title: 'Events', data: results });
});
});
router.post('/add', function (req, res) {
var obj = req.body.title;
console.log(obj);
res.redirect('/events');
});
What i see in browser
You have the 'add' endpoint listed in in your 'routes/events.js' file, which causes the structure of the final route to be '/events/add.' In your form, you are sending to the '/add' endpoint so to fix the issue, either change the action prop on the form to '/events/add' or move the '/add' endpoint into it's own route like this:
router.post('/add', function(req, res) {
var obj = req.body.title;
console.log(obj);
res.redirect('/events');
});

CSURF not working

[Development Env] nodejs v4.2.4 + expressjs v4.13.1 + csurf v1.8.3
I successfully installed csurf middleware but It seems like not working.
I tried submitting form without csrf input field to test it works and there was nothing err. So I inserted console.log codes into router js file
console.log(res.locals._csrf);
and I recieved 'undefined'.
I inserted input field to verify the value exist, html result also had not csrfToken
<input name="_csrf" value="" type="hidden">
What can I do? This is html source
<form class="form" method="post" action="/login" role="form">
<input type="hidden" name="_csrf" value="{{_csrf}}">
<div class="form-group label-floating">
<label class="control-label" for="focusedInput1">User Name</label>
<input class="form-control" name="userName" id="focusedInput1" type="text">
</div>
<div class="form-group">
<div class="form-group label-floating">
<label class="control-label" for="focusedInput2">password</label>
<input class="form-control" name="user_pw" id="focusedInput2" type="password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" style="float:left">Login</button>
<button type="button" class="btn btn-default" style="float:right" data-dismiss="modal">Cancel</button>
</div>
</form>
and This is app.js
// module importing
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
exphbs = require('express-handlebars'),
mongoose = require('mongoose'),
csrf = require('csurf');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var routes = require('./routes/index');
var users = require('./routes/users');
var credentials = require('./credentials.js');
var app = express();
// mongoose Setup
mongoose.connect(credentials.mongooseRsrc.collUrl);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', exphbs({defaultLayout: 'single', extname: '.hbs'}));
app.set('view engine', '.hbs');
// 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: true }));
app.use(cookieParser(credentials.cookieSecret));
app.use(session({
resave: false,
saveUninitialized: false,
secret: 'sfbsesc',
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(csrf());
app.use(function(req, res, next){
res.locals._csrf = req.csrfToken();
});
//skip
I had the same issue and worked around it by passing the token in through the controller.
In your routes controller, for your POST /login, pass in the token as an object on response.
router.post('/login', (req, res) => {
res.render('login', {
_csrfToken: req.csrfToken(),
});
});
This could cause issues with other routes depending on how they're set up, but if you encounter errors saying token is invalid, you probably just need to pass it into that route as well

How to get GET multiple variables in Express.js on Node.js?

I am trying to get Form data from html page to Node Js server .
My html file is index.html
<body>
<nav>
<ul>
<li>
Add Product
<div class="dialog" style="display:none">
<div class="title">Add Product</div>
<form action="" method="get">
<input id = "name" name="name" type="text" placeholder="Product Name"/>
<input name="code" type="text" placeholder="Product Code"/>
<input name="category" type="text" placeholder=" Category"/>
<input name="brand" type="text" placeholder="Brand"/>
<input type="submit" value="Ok"/>
</form>
</div>
</li>
<li class="radio">
</li>
</ul>
</div>
</nav>
<p></p>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
after submitting the form there is no action perform by the server just get the url with all details
and My server is server.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
methodOverride = require('method-override'),
hostname = process.env.HOSTNAME || 'localhost',
port = parseInt(process.env.PORT, 10) || 4004,
publicDir = process.argv[2] || __dirname + '/public';
var exec = require('child_process').exec;
var fs = require('fs');
//Show homepage
app.get("/", function (req, res) {
res.redirect("/index.html");
console.log("shubh ");
});
app.get("/index/", function (req, res) {
res.redirect("/index.html");
console.log("shubham ");
});
app.get("/index/:name", function (req, res){
console.log("shubham batra");
var keyword = req.query.code;
console.log(keyword);
//res.send('You sent the name "' + req.body.name + '".');
console.log(res.body);
});
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
//Search page
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, port);
app.listen(port);
Your form action is '', therefor the URL created by the form will be
/?name=xxx&code=yyy etc
From your routing, it seems like you're expecting the url to be in the form of /xxx?code=yyy.
Make your form action '/search' and add the following JS.
app.get("/search", function (req, res){
console.log("shubham batra");
var keyword = req.query.code;
console.log(keyword);
//res.send('You sent the name "' + req.query.name + '".');
});
As your making a get request, request.body won't be set.
You can use as multiple as you want like:
var code = req.query.code;
var category = req.query.category;
var brand = req.query.brand;
req.query if its GET request and req.body if its POST.
change the app.get("/index/:name", function (req, res){
to app.get("/index/:name?", function (req, res){
that your route will match /index/ and /index/anyname routes
and change form action to "/" or something like "/action"

Categories