Connect html contact us form with expressjs server side - html

Hi I'm new in web development I'm trying to write the backend code for contact us form but it keep giving me error:
My Html code for contact us form:
</div>
<div class="row">
<div class="col-sm-8">
<div class="contact-form">
<h2 class="title text-center">Get In Touch</h2>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form row" name="contact-form" method="post">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group col-md-6">
<input type="email" name="email" class="form-control" required="required" placeholder="Email">
</div>
<div class="form-group col-md-12">
<input type="text" name="subject" class="form-control" required="required" placeholder="Subject">
</div>
<div class="form-group col-md-12">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Your Message Here"></textarea>
</div>
<div class="form-group col-md-12">
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Submit">
</div>
</form>
</div>
</div>
and my backend code is
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var pjs = require('ejs');
var nodemailer = require('nodemailer');
var router = express.Router();
var app = express();
// Middleware
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req, res) {
// database query
res.render('index');
});
app.get('/blog-single.html', function(req, res) {
// database query
res.render('blog-single');
});
app.get('/blog.html', function(req, res) {
// database query
res.render('blog');
});
app.get('/cart.html', function(req, res) {
// database query
res.render('cart');
});
app.get('/checkout.html', function(req, res) {
// database query
res.render('checkout');
});
app.get('/contact-us.html', function(req, res) {
// database query
res.render('contact-us');
});
router.post('/contact-us.html :contact-form', function(req, res) {
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'abm.rizk#gmail.com', // Your email id
}
})
});
app.get('/index.html', function(req, res) {
// database query
res.render('index');
});
app.get('/login.html', function(req, res) {
// database query
res.render('login');
});
app.get('/product-details.html', function(req, res) {
// database query
res.render('product-details');
});
app.get('/shop.html', function(req, res) {
// database query
res.render('shop');
});
app.get('/*', function(req, res) {
// database query
res.render('404');
});
app.listen(8080, function(err) {
if (err) {
console.log("Error");
} else {
console.log("Running on port 8080");
}
})
This is my full backend code and html i just post the contact us form so basically my problem is with
router.post('/contact-us.html :contact-form', function(req,res){
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'abm.rizk#gmail.com', // Your email id
}
})
});
In the console there is no error but one I browse :
My form:
but once I click submit :

The path of route is wrong. Alter to:
router.post('/contact-us', function(req,res){
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'abm.rizk#gmail.com', // Your email id
}
})
});
I noticed this problem on their routes, but it still does not work, post the console error output.

Related

JSON POST requests empty response on Mongo

I'm try to post From HTML Form To MongoDB Atlas and following the tutorial.
used:
express js
body-parser
mongoose
I can create a request but no content.
I have no clue where's the problem.
I'm supposed to show the document in MongoDB Atlas
{
"_id": "a13d1s2bc12as3a2",
"name": "Name",
"password": "password",
"_v": 0
}
but now like this:
{
"_id": "a13d1s2bc12as3a2",
"_v": 0
}
I can connect the mongoDB.
Here my code:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const urlencoded = require("body-parser/lib/types/urlencoded");
app.use(bodyParser.urlencoded({extended: true}));
//connect mongodb
mongoose.connect("mongodb+srv://comp3421:password#cluster.o06sg.mongodb.net/db", {useNewUrlParser: true, useUnifiedTopology: true})
//create dataSchema
const notesSchema = {
username:String,
password:String
}
const Note = mongoose.model("Note", notesSchema);
//get function
app.get("/", function(req, res){
res.sendFile(__dirname + "/try.html");
})
//insert into mongodb
app.post("/", function(req, res){
let newNote = new Note({
username: req.body.username,
password: req.body.password
});
newNote.save();
res.redirect('/');
})
app.listen(3000, function(){
console.log("server is running on 3000")
})
This part is try.html and the main part of the html:
<form action="/" method="post" enctype="multipart/form-data">
<div class="f input">
<label>Username</label>
<input type="text" name="username">
</div>
<div class="f input">
<label>Password</label>
<input type="password" name="password" >
</div>
<div>
<input type="submit" value="Create account">
</div>
</form>
You need to parse request body.
You have to mention below line.
app.use(bodyParser.json());

How can we send data in MySQL when the form has set to enctype="multipart/form-data" in node.js?

This enctype="multipart/form-data" blocking me from sending my data to mysql but it is a must for multer to work. I'm trying to store the image filename to database while the file will store to my project directory ./uploads using multer framework. I've tried different queries but nothing happen. I'm hoping for you guys which have faced the same issue like mine please take a little of your time. Thank you in advance.
<form class="add-music-form" action="/save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="song-feaured-image">
<input style="display: none;" type="file" accept="image/*" id="file" name="featured_img" onchange="loadFile(event)" required>
<img id="output" class="image-preview" width="130" src="/img/rock-on.jpg" />
<label for="file" class="attach_file" style="cursor: pointer">
<i class="material-icons">attach_file</i></label>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" id="title" name="title" required>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Band name" id="band_name" name="band_name" required>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" name="audio" required>
<label class="custom-file-label" for="customFile">Select audio file</label>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a onclick="cancel()" class="btn btn-default">Cancel</a>
</div>
</form>
app.js
const path = require('path');
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const DIR = './assets/uploads/featured-img';
// Set The Storage Engine
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, DIR);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
let upload = multer({storage: storage});
// Set Database Connection
const connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'nodejs_crud'
});
connection.connect(function(error){
if(!!error) console.log(error);
else console.log('Database Connected!')
});
//set view file
app.use(express.static('assets'));
app.use(express.static(__dirname + '/assets'));
//set view engine
app.set('view engine', 'ejs');
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extend: false}));
app.get('/',(req, res) => {
let sql = "SELECT * FROM music"
let query = connection.query(sql, (err, rows) => {
if(err) throw err;
res.render('music_index');
});
});
app.get('/', (req, res) => res.render('music_index'));
app.post('/save',upload.single('featured_img'), function (req, res) {
let sql = "INSERT INTO `music`(`featured_img`, `title`, `band_name`, `audio`) VALUES ('" + req.body.featured_img + "', '"+req.body.title+"', '"+req.body.band_name+"', '"+req.body.audio+"')";
let query = connection.query(sql, (err, results) => {
if(err) throw err;
res.redirect('/');
});
});
// Server Listening
const port = 3000;
app.listen(port, () => console.log(`Server started on port ${port}`));
suggestion
reference this
your data that inserted into database isn't on req.body object instead some where else.
like req.files.file object. you can print out the log by using console.log('req.file' + req.file + 'req.files' + req.files) on your app.js file
app.post('/save',upload.single('featured_img'), function (req, res) {
console.log('req.file' + req.file + 'req.files' + req.files)
let sql = "INSERT INTO `music`(`featured_img`, `title`, `band_name`, `audio`) VALUES ('" + req.body.featured_img + "', '"+req.body.title+"', '"+req.body.band_name+"', '"+req.body.audio+"')";
let query = connection.query(sql, (err, results) => {
if(err) throw err;
res.redirect('/');
});
});
reference

MySQL store "Undefined" string in nodejs multipart/form-data?

js application with mysql server in my app I want to store the filename of the image at the same time the image file will store to my project folder. I am using this multer framework to upload my file yes I have successfully stored the image file in my project folder /uploads. But sadly MySQL wont allow me to send the data it will only store "undefined" string. How can we possibly fix this?
<form class="add-music-form" action="/save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="song-feaured-image">
<input style="display: none;" type="file" accept="image/*" id="file" name="featured_img" onchange="loadFile(event)" required>
<img id="output" class="image-preview" width="130" src="/img/rock-on.jpg" />
<label for="file" class="attach_file" style="cursor: pointer">
<i class="material-icons">attach_file</i></label>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" id="title" name="title" required>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Band name" id="band_name" name="band_name" required>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile" name="audio" required>
<label class="custom-file-label" for="customFile">Select audio file</label>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a onclick="cancel()" class="btn btn-default">Cancel</a>
</div>
</form>
app.js
const path = require('path');
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const DIR = './assets/uploads/featured-img';
// Set Database Connection
const connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'nodejs_crud'
});
connection.connect(function(error){
if(!!error) console.log(error);
else console.log('Database Connected!')
});
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, DIR);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
let upload = multer({storage: storage});
//set view file
app.use(express.static('assets'));
//set view engine
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extend: false}));
app.get('/',(req, res) => {
let sql = "SELECT * FROM music"
let query = connection.query(sql, (err, rows) => {
if(err) throw err;
res.render('music_index');
});
});
app.post('/save',upload.single('featured_img'), function (req, res) {
let sql = "INSERT INTO `music`(`featured_img`, `title`, `band_name`, `audio`) VALUES ('" + req.body.featured_img + "', '"+req.body.title+"', '"+req.body.band_name+"', '"+req.body.audio+"')";
let query = connection.query(sql, (err, results) => {
if(err) throw err;
res.redirect('/');
});
});
// Server Listening
const port = 3000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Here's an example of a single file being uploaded. To upload multiple files in the same form you'll need to use upload.array instead of upload.single:
/views/music_index.ejs:
<form class="add-music-form" action="/save" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="song-feaured-image">
<input style="display: none;" type="file" accept="image/*" id="file" name="featured_img" required>
<img id="output" class="image-preview" width="130" src="/img/rock-on.jpg" />
<label for="file" class="attach_file" style="cursor: pointer">
<i class="material-icons">attach_file</i></label>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" id="title" name="title" required>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Band name" id="band_name" name="band_name" required>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">Submit</button>
<a onclick="cancel()" class="btn btn-default">Cancel</a>
</div>
</form>
app.js:
const path = require('path');
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
// Ensure this folder exists
const DIR = './assets/uploads/featured-img';
let storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, DIR);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
let upload = multer({storage: storage});
app.use(express.static('assets'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extend: false}));
app.get('/',(req, res) => {
res.render('music_index');
});
app.post('/save',upload.single('featured_img'), function (req, res) {
let sql = "INSERT INTO `music`(`featured_img`, `title`, `band_name`, `audio`) VALUES ('" + req.file.path + "', '"+req.body.title+"', '"+req.body.band_name+"', '"+req.body.audio+"')";
console.log(sql);
});
const port = 3000;
app.listen(port, () => console.log(`Server started on port ${port}`));

how to insert data into database using MEAN stack (MySQL, Express, Angular, Node)

How to insert data into database using MEAN stack (MySQL, Express, Angular, Node)?
I am facing the problem at the time of insertion. Please help me to solve this. Here is my code. I'm newbie in MEAN.
index.html
<html ng-app="bookitnow">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<title> Registration Page </title>
</head>
<body>
<div class="container" ng-app="bookitnow" ng-controller="myCtrl">
<h1>Register</h1>
<form method="post">
<div class="form-group">
<input type="text" class="form-control" id="firstName" ng-model="fname" placeholder="First Name" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="lastName" ng-model="lname" placeholder="Last Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" ng-model="email" placeholder="Email Address" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" ng-model="phone" placeholder="Phone" required>
</div>
<button type="submit" class="btn btn-info" ng-click="submit()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</body>
</html>
server.js
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookitnow'
});
connection.connect(function(err) {
if (!err)
console.log('Database is connected');
else
console.log('DB connection error.');
});
app.use(express.static(__dirname + '/public'));
app.get('/index.html', function(req, res){
res.sendFile(__dirname + '/public' + 'index.html');
});
app.post('/index.html', function(req, res, next) {
var data = req.body;
console.log('request received:', data);
connection.query('INSERT INTO register SET ?', data, function(err,res){
if(err) throw err;
console.log('record inserted');
});
app.listen(5500);
console.log('Hi from server.js');
controller.js
var app = angular.module('bookitnow',[]);
app.controller('myCtrl', function($scope,$http){
$scope.submit = function() {
var data = {
fName : $scope.fname,
lName : $scope.lname,
email : $scope.email,
phone : $scope.phone
}
};
$http.post('/index.html', &scope.data)
.success(function (data, status, headers, config) {
$scope.result = data;
console.log("inserted successfully")
})
.error(function(data, status, header, config){
$scope.result = "Data: " + status;
});
In your controller.js, try the following and see what happens.
var app = angular.module('bookitnow',[]);
app.controller('myCtrl', function($scope, $http){
$scope.submit = function() {
var data = {
fName : $scope.fname,
lName : $scope.lname,
email : $scope.email,
phone : $scope.phone
};
$http
.post('/index.html', data)
.then(function (response) {
console.log(response)
}, function(response){
console.log(response)
});
};
});

How to send the response to the same html page after clicking submit button using node.js

Onclick of submit button,I'm redirecting the data "name" to this url http://localhost:3000/getfileNames.But, now I'm trying to get the data "name" to same html page(http://localhost:3000/login).Can anyone please help me out regarding this ...
My sample.html:
<html>
<head>
</head>
<h1>
Login
</h1>
</head>
<body>
<div id="formContainer">
<form method="post" action="/getfileNames">
Name: <input type="text" name="name" id="name" placeholder="name"> <br><br>
Password: <input type="text" name="pwd" id="pwd" placeholder="password"> <br><br>
<input type="submit" name="submit" value="submit" />
</form>
</div>
</body>
</html>
My index.js:
var express = require('express');
var router = express.Router();
router.get("/login", function(req, res)
{
res.sendFile("login.html", {"root": __dirname});
});
router.post('/getfileNames', function(req, res) {
console.log(req.body.name);
res.send('Name: ' + req.body.name);
});
module.exports = router;
If you want to build some kind of auth, I suggest to use server-side template system e.g. Jade.
So your code would be like:
var express = require('express');
var router = express.Router();
router.get("/", function(req, res)
{
if(req.user)
res.render('index', {user: req.user.name})
else res.redirect('/login');
});
router.get('/login', function(req, res) {
res.render('login');
});
router.post('/login', function(req, res) {
/* Log user in, set cookies, whatever */
res.redirect('/');
});
In top of the app you have to use some some auth middleware (e.g. passport.js or write it by yourself).
Of course, you can just make AJAX to get user name but I don't think it's a good solution in this case.
UPDATE
If you just want to show some text you stored on server.
index.js
<html>
<head>
</head>
<h1>
Login
</h1>
</head>
<body>
<p id="savedName"></p>
<div id="formContainer">
<form>
Name: <input type="text" name="name" id="name" placeholder="name"> <br><br>
Password: <input type="text" name="pwd" id="pwd" placeholder="password"> <br><br>
<button name="submit" value="submit" id="btn"/>
</form>
</div>
</body>
</html>
client.js
$(function(){
$.get('/name').done(fucntion(name){ $('#savedName').text(name) }).fail(alert);
$('#btn').click(function(){
var name = $('#name').val();
var pwd = $('#pwd').val();
$.post('/name', {name: name, pwd: pwd}).done(fucntion(){ $('#savedName').text(name) }).fail(alert);
})
})
server.js
var express = require('express');
var router = express.Router();
var name = "";
router.get("/", function(req, res)
{
res.sendFile("login.html", {"root": __dirname});
});
router.get('/name', function(req, res) {
res.send(name);
});
router.post('/name', function(req, res) {
name = req.body.name;
res.senStatus(200);
});