Contact us form Node Js/express 404 error - html

I am trying to create an form that allows a person to send me an email.
However, I am getting a 404 error, shown below.
The form itself is rendering, so what I have in index.js is working.
Do I need some additional code somewhere else or am I missing a few additional pieces of code.
I have nodemailer etc and all the necessary packages installed too.
I am very new to this and I would appreciate any help.
Thank you!
404 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 nodemailer = require('nodemailer');
var index = 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', '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: 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
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.post('/contactus', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "me#gmail.com",
pass: "xxxxxx"
}
});
//Mail options
mailOpts = {
from: req.body.name + req.body.email,
to: 'yyyyyyyyyy#gmail.com',
subject: req.body.email + ' --Msg from contactus-form',
text: "Name: " + req.body.name + "Email: " + req.body.email +
"Contact No: " + req.body.contactNo + "QUERY: " + req.body.message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Alert on event of message sent succeeds or fail.
if (error) {
res.render('contactus',{msg : 'Error occured, message not sent.', err : true});
}
else {
res.render('contactus',{msg : 'Message sent! Thank you.', err : false});
}
smtpTrans.close();
});
});
// 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;
contactus.hbs
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div class="content">
<form action="/contactus" method="post">
<fieldset>
<p>
<input type="text" name="name" size="30" required="" placeholder="Name:">
</p>
<p>
<input type="text" name="contactNo" size="30" placeholder="Contact No.:">
</p>
<p>
<input type="text" name="email" size="30" required="" placeholder="Email:">
</p>
<p><br>
<textarea type="text" name="message" cols="37" rows="7" size="30" placeholder="Your message please"></textarea>
</p>
<p>
<input name="submit" type="submit" value="Send" id="submit">
</p><br>
</fieldset>
</form>
</div>
</body>
</html>

This handler:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Should be moved to just before the 500 error handler.
The reason, it acts as a catch all. Meaning it will always execute if something before it did not route some place first. So it runs and sends the 404 before it has a chance to get to the contactus route.

Related

Cannot POST /ha use more then one FORM

I was trying to send more then one FORM, but I get an error.
The first FORM works the second one doesn't. It's the same form.
The second one gives me an error Cannot POST /ha
<body>
<form action="/ha" method="post">
<input type="text" name="user">
<input type="submit" value="Senden">
</form>
<form action="/Gehalt" method="post">
<input type="text" name="user">
<input type="submit" value="Senden">
</form>
</body>
this is my test.js
const sqlite3 = require('sqlite3').verbose();
const express = require('express');
const bodyParser = require('body-parser')
var app = express();
let Gehalt
let r
app.use(bodyParser.urlencoded({
extended: true
}));
let db = new sqlite3.Database('memory.sqlight3', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/test.html');
});
app.post('/ha', function(req, res) {
console.log("Yout got it");
r = req.body.user;
var stmt = db.prepare('INSERT INTO lorem (Salary) VALUES(?);');
stmt.run(r);
stmt.finalize();
db.close();
});
app.post('/Gehalt', function(req, res) {
console.log("Yout got it");
r = req.body.user;
var stmt = db.prepare('INSERT INTO lorem (Outgoings) VALUES(?);');
stmt.run(r);
stmt.finalize();
db.close();
});
app.listen(3100, function() {
console.log('GO to Port 3100');
});
What did I do wrong?

Sending HTML template through mail using node js node mailer

I had written node mailer code from w3schools. I want to send the html template designed (index.html in my case). Below is the code. please help me how can i send html template to the mail using node js.
var nodemailer = require('nodemailer');
var data = require('index.html');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
html: 'data'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
This is the right way of passing html in the nodemailer
var nodemailer = require('nodemailer');
var fs = require('fs');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
fs.readFile('index.html', {encoding: 'utf-8'}, function (err, html) {
if (err) {
console.log(err);
} else {
var mailOptions = {
from: 'youremail#gmail.com',
to: 'myfriend#yahoo.com',
subject: 'Sending Email using Node.js',
html: html
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
});
Index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Node js Email </title>
<link rel="stylesheet" href="">
</head>
<body>
<div class="container"><br />
<h1>Send Email</h1><br />
<form onsubmit="sentthis()" method="post">
<div class="divi">
<label for="to"></label>To:</label>
<input type="email" class="too" name="to">
</div>
<div class="divi">
<label for="subject">Subject:</label>
<input type="text" class="subjectt" name="subject">
</div>
<div class="divi">
<p>Body:</p>
<textarea cols="" rows="5"class="textarea" name="body"></textarea>
</div>
<div class="divi">
<button type="submit" class="btn">Send</button>
</div>
</form>
</div>
</body>
</html>
server.js file
var express = require('express'),
path = require('path'),
nodeMailer = require('nodemailer'),
bodyParser = require('body-parser');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index.html');
});
app.post('/sent',function(req,res){
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'marcus251#gmail.com',
pass: 'yourpassword'
}
});
let mailOptions = {
from: '"Marcus coffee" <marcus251#gmail.com>',
to: "Receiver Name <receiver#email.com>",
subject: req.body.subject,
text: req.body.body,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: ', info.messageId, info.response);
res.render('index.html');
});
});
app.listen(port, function(){
console.log('Server is running at port: ',port);
});
This will solve your problem.

hot to access username present in login.html to index.js in node.js

i am accessing the username field from the login.html file present in public folder to index.js file which is outside of public folder.
here is my login.html code which is in public folder
<!DOCTYPE html>
<html>
<head>
<title>login</title>
</head>
<body>
<h2> login to chat application </h2>
<form method = "post" action='/user'>
<div class="container">
<label><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="name" >
<button type="submit">Login</button>
</div>
</div>
</form>
</body>
</html>
here is my index.js file which is outside of public folder and i a accessing through route /user.
var express = require('express');
var socket = require('socket.io');
var mongoose = require('mongoose');
var app = express();
var dbPath = "mongodb://localhost/chat";
// command to connect with database
db = mongoose.connect(dbPath);
mongoose.connection.once('open', function() {
console.log("database connection open success");
});
var server = app.listen(8000,function(){
console.log("The server is listening on the port 8000");
});
app.use(express.static('public'));
app.get('/user', function(req,res){
res.sendFile(__dirname + '/public/login.html');
})
app.post('/user', function(req,res){
if(req.body.name === undefined){
console.log("user not found");
}
else{
console.log("upto here")
res.sendFile(__dirname + '/public/index.html');
}
})
var io = socket(server);
io.on('connection', function(socket){
socket.on("chat", function(data){
io.sockets.emit("chat", data);
});
socket.on("typing", function (data){
socket.broadcast.emit("typing", data);
});
});
i have chat application accesing username from frontend page and using it to the chat file.
here i am unable to accessing the name="username" field to req.body.username please rectify me.
You need to use the body-parser package : https://www.npmjs.com/package/body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

How do I POST data into MongoDB database using node.JS?

the code below is pretty messy so don't judge too much! I am trying to POST a basic user profile into my database, i don't think i am far off but i keep getting a 404.
im pretty knew to all of these technologies so could somebody please enlighten me as to what i have done wrong.
node.js POST method
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/local';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('signIn', { title: 'signIn' });
});
router.get('/getData', function(req, res, next){
mongo.connect(url, function (err, db) {
assert.equal(null, error);
var cursor = db.collection('userData').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
} );
});
});
router.post ('/insert', function(req,res,next) {
var item = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
password: req.body.password
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('userData').insertOne(item, function (err, result) {
assert.equal(null, err);
console.log('item has been inserted');
db.close;
});
});
res.redirect('/');
});
module.exports = router;
form HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>SignIn Page</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/signIn.css"/>
</head>
<body>
<div class="background">
<div class="loginFormWrapper">
<form action="/users/submit" method="POST">
<div class="loginForm">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="first name">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="last name">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="password">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="users" method="GET">
<button type="submit" class="btn btn-default">get result</button>
</form>
</div>
</div>
</body>
</html>
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 validate = require('form-validate');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var About = require('./routes/about');
var signIn = require('./routes/signIn');
var contact = require('./routes/contact');
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: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/About', About);
app.use('/signIn', signIn);
// app.use('/contact', contact);
//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;
user.js
var express = require('express');
var app = require("mongoose");
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
A quick reminder, the post() method just gets the data from the <form> you specify. For you to be able to get that data you'd have to do something like this.
app.js
const express = require('express)
const mongoose = require('mongoose)
var app = express()
mongoose.connect('mongodb://localhost:"yourPortHere"/"mongoDBhere"')
Now post needs the body parser in order to be able to retrieve the data and sort of "translate it" to JS, for that you need the body parser.
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
Now let's get to the post
app.post("/action", (req, res) => {
var userData = {
username: req.body.username,
password: req.body.password
}
For the moment userData is going to hold the data you just retrieved from the <form>
Remember that action="/YourActionHere is the identifier for the app.post("/YourActionHere") so those two have to match, otherwise you will not get the data.
To save it to MongoDB you first need to create a model of the object you want to store, if MongoDB has a Database named movies with a directory named films on it you first have to create a Model named film since mongoose will save it in the directory films (<- By directory I mean collection)
So: in folder Models you create a model of the object
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var film = new Schema({
title: String,
year: String,
director: String
})
module.exports = mongoose.model("movie", movieSchema)
To be able to use that new Schema you have to import it in you app.js with
var Film = require('pathToFilmSchema')
Now in your post you will save userData to that Schema, and mongoose will store it in the collection specified in its .js.
app.post("/action", (req, res) => {
var userData = {
title: req.body."name",
year: req.body."name",
director: req.body.""
}
new Film(userData)
})
If the structure is the same de Data in that variable will be stored in a Schema, then you just have to call the method .save(), which you can call right after like this
newFil(userData)
.save()
Now mongoose will store a new object with film Schema into the database you have connected at the top. Keep in mind that, if you don't have a collection named film mongoDB will create one collection named films (the plural, always) and store the Schema there.
After saving you can res.redirect() to "/" or render another page, that's up to you.
You have posted to url users/submit but i don't see any API for users/submit . You have said to use users for /users urls but have you defined the /submit within /users?
You could go through this
Routing in expressjs
Inside your app.post function you should have something like this:
let MongoClient = require('mongodb').MongoClient;
let connectionUrl = "mongodb://localhost:27017/";
// or
// let connectionUrl = "mongodb+srv://<username>:<password>#<your-cluster-url>/test?retryWrites=true&w=majority";
// creating the message object
let obj = {"text" : "Something"};
console.log("OBJ: " + obj);
MongoClient.connect(connectionUrl, function(err, client) {
if (err) throw err;
console.log("Connected correctly to server");
// if database and collection do not exist they are created
var db = client.db('YourDatabase')
db.collection("YourCollection").insertOne(obj, function(err, res) {
if (err) throw err;
console.log("1 message inserted");
client.close();
});
});

How to merge node.js and html?

I have an html file (home.html) and a node.js file (app.js).I used mysql also.What i have now is the app.js that is the server side that looks like this:
var application_root = __dirname,
express = require("express"),
mysql = require('mysql');
path = require("path");
var app = express();
var http = require('http');
var connection = mysql.createConnection({host : '127.0.0.1',user : 'root', password : '',database: "medical"
});
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.get('/getallusers/:email', function (req, res) {
connection.connect();
//var json = '';
connection.query('SELECT * FROM users where email = '+req.params.email, function (error, rows, fields) {
str='';
for(i=0;i<rows.length;i++)
str = str + rows[i].email +'\n';
// res.end( str);
res.end( str);
// json = JSON.stringify(rows); //displaying json file
//res.send(json);
});
connection.end();
});
And in my home.html i have a text box and a button that represents a search action to do that retrieves data from the database :
<div class="search" id = "page_content1">
<h1>Enter Candidate's email: </h1>
</br>
<form method="get" action="http://127.0.0.1:1212/getallusers/email">
<input type="text" name="email" id="email">
<input type="submit" name="commit" value="search" id = "search" onclick="display()"/>
</form>
</div>
Now I want to have the results retrieved by the query in app.js file to be displayed in my home.html file,any help on how to do that?