cannot post form in node.js express - javascript

I am very much beginner with node.js.
There is a sample form with that I am trying to insert values in database-
Here is my test page-
<form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencoded">
<input type="text" id="username_input" name="username">
<input type="text" id="password_input" name="password">
<input type="submit" name="Submit" value="Insert" class="btn">
</form>
Trying to post it-
I created test.js file and writing post method in it-
exports.list = function (req, res) {
req.getConnection(function (err, connection) {
console.log(con)
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
});
}
But this didn't work.
I tried writing post method in main server.js file also-
app.post("/create", function (req, res) {
var username = req.body.username,
password = req.body.password;
console.log(username);
console.log(password);
connection.query('INSERT INTO users(email,password) VALUES', (username, password), function (err, rows) {
if (error) {
console.log(error.message);
} else {
console.log('succes');
}
});
});
but this didn't work also.
I am following current settings in server.js file-
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, index_form = require('./routes/index_form')
, user = require('./routes/user')
, test = require('./routes/test')
, mysql = require('mysql')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass#123'
});
var app =express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test', test.test);
app.get('/users', user.list);
app.get('/index_form', index_form.index_form)
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
Kindly guide me through this all , How do I make my form post with node.js?

Did you try putting app.post("/create", test.test); into your current server.js after your GET routes yet? Because what I saw here your current server.js does not have any POST request.

Related

contact form works on local host but not on html page

I'm using node and express to send email through html page.
Following is my app:
`const express = require('express');
const path = require('path');
const nodeMailer = require('nodemailer');
const bodyPaser = require('body-parser');
const app = express()
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.set('view engine', 'html');
app.use(express.static('public'));
app.use(bodyPaser.urlencoded({ extended: true }));
app.use(bodyPaser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index.html');
app.locals.layout = false;
});
//internet connectivity check out
function checkInternet(cb) {
require('dns').lookup('google.com', function (err) {
if (err && err.code == "ENOTFOUND") {
cb(false);
} else {
cb(true);
}
})
}
app.post('/', (req, res) => {
const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>
<li>Name:${req.body.name}</li>
<li>Email:${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
// create reusable transporter object using the default SMTP transport
let transporter = nodeMailer.createTransport({
host: "mail.example.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: 'contact#example.com', // generated ethereal user
pass: 'Y#$972200424' // generated ethereal password
},
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let mailOptions = {
from: `${req.body.email}`, // sender address
to: "contact#example.com", // list of receivers
subject: "Customer Message", // Subject line
text: `SenderName: ${req.body.name}, --Message: ${req.body.message}`, // plain text body
html: output // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodeMailer.getTestMessageUrl(info));
if (info.messageId) {
res.redirect('back');
res.send(true);
}
});
});
app.listen(3000, () => console.log('server is running at port 3000'));`
the thing is it sends email and works fine on localhost:3000 but the same does NOT work on index.html page.
how can I have it to send email on the html page?
Simply move html files to the public directory below
You must be change
app.use(express.static('public'));
to
app.use(express.static(`${__dirname}/public`));
also change:
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
to
app.get('/', function (req, res) {
res.sendFile(path.join(`${__dirname}/public/index.html`));
});
Follow the order of the lines:
app.use(express.static(`${__dirname}/public`));
app.get('/', function (req, res) {
res.sendFile(path.join(`${__dirname}/public/index.html`));
});
Also you can use template engine pug. see this doc:
Using template engines with Express

Cannot POST form - ExpressJS

I'm learing ExpressJS, i want to do the login part , but i gave me this
Cannot POST /login
im using the post method why it gave me this error
here a detailed post , thank you in advance for helping me
html part
<form method="POST">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" >
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password">
<button type="submit">Login</button>
</div>
</form>
The route.js
router.post('/login'),(req,res)=>{
var username= req.body.name;
var password = req.body.password;
con.query('SELECT * FROM authentication WHERE username = ?',username, function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if(results[0].password == password){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"username and password does not match"
});
}
}
else{
res.send({
"code":204,
"success":"username does not exits"
});
}
}
});
}
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
when trying to post this form i'm getting:
Cannot POST /login
what am i missing here?
You should handle current page, not '/login' page in route.js :
router.post('/', //...
Instead of writing
router.post('/login', //...
Because you sent the form data to the current page not to the '/login' page
Why current page ?
Because, you didn't define action attribute in your form
You need to define form action
<form action="/login" method="post">
But I recommend you to use js for sending requests
fetch('/login', {
method: 'POST',
body: JSON.stringify(yourFormData),
// ...another Opts if it needs
})
Also it can be problem with your server code because I don't see defining router in indexRouter file, you should add it:
const express = require('express');
const router = express.Router();
// then your code:
router.post('/login', loginController);
But you can add this line for check post requests:
app.post('/login', (req, res) => {
res.status(201).json(req.body); // or console.log
});

Login and registration using Nodejs + express, user data undefined

I have a simple registration page which should store the users input (name,email,password) in a database. I am using express and node. The thing i wanted to try is to have all the database operations (insert,select etc) for registration in one file and send the response to the server from another file.
dbQuery.js
var express=require("express");
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user_name',
password : 'password',
database : 'database'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports.register=function(callback){
app.get('/register',function(req,res){
var today = new Date();
var users={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
return connection.query('INSERT INTO users SET ?',users, callback)
}
}
app.js
var express=require("express");
var connection = require('./dbQuery');
var app = express();
app.post('/register',function(req,res){
connection.register(function(error, results, fields){
if (error) {
res.json({
status:false,
message:'there are some error with query for registration'
})
}else{
console.log('is it coming here in else')
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
})
})
index.html
<html>
<body>
<form action="/register" method="POST">
First Name: <input type="text" name="name">
Email: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit" value="Submit">
</form>
</body>
</html>
When i execute app.js the server just keep loading without giving anything
I expected the output should be displaying the json response on server i.e 'user successfully registered' ,but it keeps on loading.
Try changing dbQuery.js to this:
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "user_name",
password: "password",
database: "database"
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports.register = function(callback) {
var today = new Date();
var users = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created_at: today,
updated_at: today
};
connection.query("INSERT INTO users SET ?", users, callback);
};
You are doing wrong, here if am posting simple steps for an API by express
Your app.js file should be
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const i18n = require("i18n");
var indexRouter = require('./routes/index');
// this is the api file created under the routes folder
var apiRouter = require('./routes/api');
require('./database')
var app = express();
app.use(i18n.init);
i18n.configure({
locales: ['en', 'de'],
cookie: 'LocalLang',
defaultLocale: 'en',
extension: ".json",
directory: __dirname + '/locales',
register: global,
logDebugFn: function (msg) {
console.log('debug', msg);
},
logWarnFn: function (msg) {
console.log('warn', msg);
},
logErrorFn: function (msg) {
console.log('error', msg);
}
});
// 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')));
app.use('/', indexRouter);
app.use('/api', apiRouter);
// 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('pages/error');
});
module.exports = app;
In you api.js file which is required in app.js file
var express = require('express');
var router = express.Router();
//Import your query.js file
const query = require('path for the file ./query')
router.post('/register',query.register)
module.exports = router;
query.js file should be like
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user_name',
password : 'password',
database : 'database'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
exports.register = (req, res)=>{
var today = new Date();
var users = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created_at: today,
updated_at: today
};
connection.query("INSERT INTO users SET ?", users, (error,result)=>{
if(err)
return res.send({status:false, message:"Error in savind data in db"})
return res.send({status:true, message:"Resgistered sucessfully"})
});
}

Invalid session token with parse-server, node.js, and express

I am trying to log in a user from a web site. I am using parse-server hosted at Microsoft Azure. I keep getting the following error, just trying to access the home page:
Error handling request: ParseError { code: 209, message: 'invalid session token' } code=209, message=invalid session token
And the browser throws a "...redirected you too many times." error. I'm not sure what I'm doing wrong, I've tried researching and piecing this together from here: https://github.com/ParsePlatform/parse-server/issues/497 with no luck.
index.js
var express...
etc...
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});
//Server configuration
...
//Express configuration
var app = express();
app.use(cookieParser()); // read cookies (needed for auth)
// get information from html forms
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use('/public', express.static(__dirname + '/public'));
app.use('/parse', new ParseServer(config.server));
app.use('/parse-dashboard', ParseDashboard(config.dashboard, true));
app.use(cookieSession({
name: "COOKIE_NAME",
secret: "COOKIE_SECRET",
maxAge: 15724800000
}));
app.use(function (req, res, next) {
Parse.Cloud.httpRequest({
url: 'https://localhost:1337/parse/users/me',
headers: {
'X-Parse-Application-Id': process.env.APP_ID,
'X-Parse-REST-API-Key': process.env.API_KEY,
'X-Parse-Session-Token': req.session.token
}
}).then(function (userData) {
req.user = Parse.Object.fromJSON(userData.data);
next();
}).then(null, function () {
return res.redirect('/login');
});
});
app.use(flash()); // use connect-flash for flash messages stored in session
//routes
require('./routes/routes.js')(app);
app.listen(process.env.PORT || url.parse(config.server.serverURL).port, function () {
console.log(`Parse Server running at ${config.server.serverURL}`);
});
routes.js
// app/routes.js
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({extended:false});
module.exports = function(app) {
// HOME PAGE ========
app.get('/', function(req, res) {
res.render('index.ejs', { title: 'Audiomesh' }); // load the index.ejs file
});
// LOGIN ===============================
// show the login form
app.get('/login', function(req, res) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
req.session.user = user;
req.session.token = user.getSessionToken();
res.redirect('/dashboard');
}, function(error) {
req.session = null;
res.render('login', { flash: error.message });
});
});
// DASHBOARD =====================
app.get('/dashboard', function(req, res) {
res.render('dashboard.ejs', {
user : req.user // get the user out of session and pass to template
});
});
// LOGOUT ==============================
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
login.ejs
<body>
<p><%= message %></p>
<form name="loginForm" action="/login" method="post">
<label>Email</label>
<input type="email" name="email"></input>
<label>Password</label>
<input name="password" type="password"></input>
<input class="button" type="submit" value="Log In">
</form>
<p>Coming soon azure</p>
<p>Back to home page</p>
</body>
The goal of my web site is for the home page to be an advertising/landing page for the mobile app. So if you're logged in, there's no evidence here. Once you click "Login" then it would check if the user is logged in and either load their dashboard (if true), or the login page (if false).
The problem right now is I can't even load the home page. I get too many redirects.

Node.js express post parameters always undefined

I am pretty new to Node.js development, and I am aware that there are several stack overflow questions like this already, unfortunately none seem to fix my problem. So I feel all I can do is ask my question
So I am use Node.js with Express and the Jade view engine.
I based some of my code on this article : http://howtonode.org/express-mongodb
Anyway here is what I have
The node app :
var express = require('express');
var home = require('./routes/home');
var d3demo = require('./routes/d3demo');
var PersonProvider = require('./public/javascripts/personProvider').PersonProvider;
var personProvider = new PersonProvider('localhost', 27017);
var LinkProvider = require('./public/javascripts/linkProvider').LinkProvider;
var linkProvider = new LinkProvider('localhost', 27017);
var http = require('http');
var path = require('path');
var app = express();
//=============================================================================
// EXPRESS SETUP
//=============================================================================
app.configure(function(){
app.set('port', process.env.PORT || 2000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
//app.use(require('connect').bodyParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
//=============================================================================
// ROUTING
//=============================================================================
app.get('/home', function (req, res) {
home.homeGet(req, res, commonHelper, personProvider, linkProvider);
});
app.post('/home', function (req, res) {
home.homePost(req, res, personProvider);
});
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
and this is the Home route
/*
* GET home page.
*/
exports.homeGet = function(req, res, commonHelper, personProvider, linkProvider){
commonHelper.seedData(personProvider, linkProvider, function() {
res.render('home');
});
};
exports.homePost = function (req, res, personProvider) {
var newUserEmail = req.body.email;
console.log(req.body.length);
//console.log(x);
//var email = req.param('Email');
console.log("/Home posted Email :" + newUserEmail);
personProvider.save({
//email: req.param('Email'),
email: newUserEmail,
}, function (error, docs) {
if(error == null) {
res.redirect('/d3demo');
} else {
res.render('home');
}
});
};
And this is the jade view
extends layout
block head
link(rel='stylesheet', href='/stylesheets/home.css')
script(src='/javascripts/home.js')
block content
form(method='post', id='homeForm', action='http://localhost:2000/home')
div(id='dialog', title='error', style='display:none;')
p You need to supply a valid email
div(id='NewDetailsArea')
p Enter your email address, and then click enter
| <input type="text" id="email" class="email"></input>
div#homeSubmit
input(type='submit', value='Enter', id='enterEmail')
Which gets rendered to this
<form method="post" id="homeForm" action="http://localhost:2000/home">
<div id="dialog" title="error" style="display:none;">
<p>You need to supply a valid email</p></div>
<div id="NewDetailsArea">
<p>Enter your email address, and then click enter </p>
<input type="text" id="email" class="email">
</input><div id="homeSubmit"><input type="submit" value="Enter" id="enterEmail">
</div>
</div>
</form>
So the problem:
Well the problem is actually pretty simply. Within the function
homePost = function (req, res, personProvider)
I would like to be able to get the value of the 'email' form field
I have tried req.param('email'), req.body.email I have tried the standard express.bodyParser() and also the connect (which someone mentioned in another answer) one require('connect').bodyParser(), but alas all I get is undefined.
Also if I try and console.log(req.body) I get undefined
What am I doing wrong?
You need to supply a name attribute for the email input. The name is what gets sent when the form is submitted:
<input type="text" id="email" name="email" class="email">

Categories

Resources