Nothing is happening after hitting the submit button on my form. Not an error nothing happens. I'm using node.js with express and nodemailer to submit my form. Most of the questions related to this are php and aren't in this area. Any help you give would be greatly appreciated.
Here's my server.js:
app.post('/contact', function (req, res) {
//Check if all required fields are filled
if (!req.body.name || !req.body.email || !req.body.message) {
res.render('contact', {
title: 'Contact',
err: true,
page: 'contact',
type: 'empty',
body: req.body.message,
name: req.body.name,
email: req.body.email,
msg: 'Thanks.',
description: 'Email is successful'
});
return;
}
//Set up smtp mailer
smtpTrans = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: "madeforgoggl#gmail.com",
pass: ""
}
});
//Fill mail options
mailOpts = {
from: req.body.name + '<' + req.body.email + '>', // grab form data from the requet body
to: 'madeforgoggle#gmail.com',
subject: 'Website contact',
text: req.body.message + ' || NAAM:' + req.body.name + ' || EMAIL:' + req.body.email
};
smtpTrans.sendMail(mailOpts, function (error, info) {
//Email not sent
if (error) {
//console.log(error)
res.render('contact', {
title: 'Contact',
page: 'contact',
type: 'error',
description: 'Email not successful'
});
}
// Yay!! Email sent
else {
res.render('contact', {
title: 'Contact',
page: 'contact',
type: 'success',
description: 'Email successful'
});
}
});
});
Here is my form- Changed the button action to a input submit because I thought that was the problem:
<form action="/contact" id="contact-form" method="post" role="form">
<div class="form-group">
<input id="yourname" type="text"name="name" placeholder="name" class="form-control" required size="40" />
</div>
<div class="form-group">
<input id="yourcompany" type="text" name="company" placeholder="company" class="form-control" required size="40" /> <
</div>
<div class="form-group">
<input id="youremail" type="email" name="email" placeholder="email" class="form-control" required size="40" /> <
</div>
<div class="form-group">
<textarea id="yourmessage" name="message" class="form-control" placeholder="MESSAGE" required size="40" rows="10"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-block btn-danger">
Send Message
</input>
I've been working on this since 4 am and can't seem to figure out what is wrong. Any help is greatly appreciated.
Related
I am trying to fetch data from client side when i make a post request I get this error , I am new to the mongoDB and Node.js please help
I don't understand this error that why this is coming please help to resolve it
this is my schema code
`
import mongoose from "mongoose";
const signupTemplate = mongoose.Schema({
Name: {
type: String,
required: true,
},
Phone: {
type: Number,
required: true,
},
Email: {
type: String,
required: true,
},
Password: {
type: String,
required: true,
},
date: {
type: Date,
Default: Date.now,
},
});
export default mongoose.model("users", signupTemplate);
`
this is my router code
`
router.post("/signup", (req, res) => {
const signedUpUser = new signUpTemplate({
Name: req.body.Name,
Phone: req.body.Phone,
Email: req.body.Email,
Password: req.body.Password,
});
console.log(req.body.Name);
signedUpUser
.save()
.then((data) => {
res.json(data);
})
.catch((err) => {
res.json(err);
// console.log('you made an error');
});
// res.send("User Registered successfully");
});
`
this is my form code
`
<form action="/signup" method="post">
<label for="Name">Full Name</label>
<input type="text" class="form-control" id="Name" name="Name" />
<label for="Phoneno">Phone No.</label>
<input type="text" class="form-control"id="Phoneno" name="Phone" />
<label for="Email">Email</label>
<input type="email" class="form-control"id="Email" name="Email" />
<label for="create-password">Create Password</label>
<input type="password" class="form-control"id="create-password" name="Password" />
<label for="confirm-password">Confirm Password</label>
<input type="password" class="form-control"id="confirm-password" name=" Confirm-password" />
<button type="submit" class="btn">Sign Up</button>
<hr>
<p style="display:inline;">Or continue with</p>
<i class="fa-brands fa-google"></i>
<i class="fa-brands fa-facebook"></i>
<i class="fa-brands fa-instagram"></i>
</form>
`
Hey do you have the express urlencoded middleware in your index.js or server.js and if not add this line of code
app.use(express.urlencoded({ extended: true }));
I want to add a user to my database. But I couldn't add a user.I played on the user schema as much as I could, but I still couldn't get a record in the database. What should I do?
//routes/user.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const User=require('../models');
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
// #route POST api/users
// #dsc Register a user
// #access Public
router.post(
'/',
[
check('name', 'Please add a name').notEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please Enter a password for 6 or more characters'
).isLength({ min: 6 }),
check('address', 'Please include a valid address').notEmpty(),
check('location', 'Please include a valid location').notEmpty(),
check('phone', 'Please include a valid number').isLength(10),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password, address, location, phone } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ msg: 'User already exists' });
}
user = new User({
name,
email,
password,
address,
location,
phone,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{
expiresIn: 3600000,
},
(err, token) => {
if (err) throw err;
res.json({ token: token, userId: user.id }rot);
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
module.exports = router;
//frontend user.js
import React, { Component } from "react";
import { Redirect, Link } from "react-router-dom";
import Home from "./Home";
import "./signup.css";
import img from "./cart-removebg-preview.png";
import img1 from './WhatsApp Image 2020-09-18 at 17.35.32.jpeg';
import Axios from "axios";
import { localsName } from "ejs";
class Signup extends Component {
constructor(props) {
super(props);
this.signup = this.signup.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
email: "",
password: "",
name: "",
phone: "",
address: "",
location: "",
valid: false,
userId: "",
};
}
signup = async (e) => {
e.preventDefault();
await Axios.post("/api/users", {
name: this.state.name,
email: this.state.email,
password: this.state.password,
address: this.state.address,
location: this.state.location,
phone: this.state.phone,
})
.then((res) =>
this.setState({ valid: res.data.token, userId: res.data.userId })
)
.catch((err) => console.log(err));
};
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
});
}
render() {
if (this.state.valid) {
localStorage.setItem("token", this.state.valid);
localStorage.setItem("userId", this.state.userId);
}
if (this.state.valid) return <Redirect to="/"></Redirect>;
return (
<div className='signup'>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">Stud-Shop</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li className="nav-item">
<i className="fas fa-home"></i>
</li>
<li className="nav-item">
Login
</li>
</ul>
</div>
</nav>
<img src={img} className='mobSignup'/>
<div className="row">
<div className="col-lg-3 bg-white rounded ">
<div className='card'>
<form>
<div className="form-group">
<h3>Sign-Up</h3>
<label htmlFor="exampleInputEmail1"><i class=" fa-lg fas fa-envelope"></i></label>
<input
type="email"
name="email"
className="form-control"
aria-describedby="emailHelp"
placeholder="Email-Address"
value={this.state.email}
onChange={this.handleChange}
></input>
<small className="form-text text-muted">
we'll never share your email with anyone!
</small>
<label><i class=" fa-lg fas fa-key"></i></label>
<input
value={this.state.password}
name="password"
type="password"
placeholder="Password (Min Length-6)"
className="form-control"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
<label><i class=" fa-lg fas fa-user"></i></label>
<input
type="text"
name="name"
className="form-control"
placeholder="Name"
aria-describedby="emailHelp"
onChange={this.handleChange}
value={this.state.name}
></input>
<label><i class=" fa-lg fas fa-phone"></i>.</label>
<input
value={this.state.phone}
name="phone"
type="Number"
placeholder="Ph No. (Ex-98765XXXXX)"
className="form-control"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
<label><i class=" fa-lg fas fa-home"></i></label>
<input
value={this.state.address}
type="text"
name="address"
className="form-control"
placeholder="Address"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
<label><i class=" fa-lg fas fa-map-marked"></i></label>
<input
value={this.state.location}
type="text"
name="location"
className="form-control"
placeholder="Location (City)"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
</div>
<button
type="submit"
onClick={this.signup}
className="btn btn-primary"
>
Sign-Up <i className=" fas fa-check"></i>
</button>
</form>
</div>
</div>
<div className='col-lg-8'>
<img src={img} className='signupImg'/>
</div>
</div>
</div>
);
}
}
export default Signup;
//model.js
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
phone: {
type: Number,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},},
{
collection:"Users"}
);
const model = mongoose.model('UserSchema', UserSchema)
module.exports = model
database connection is established. I tried to get the code from outside, but when I tried it with my code, it didn't work. What should I do? Can you help me?
The code works well and perfectly when i use Postman to make the requests. But whenever I send the same request from the frontend I get this error.
Result {
formatter: [Function: formatter],
errors: [
{
value: undefined,
msg: 'Please enter your name',
param: 'name',
location: 'body'
},
{
value: '',
msg: 'Please enter a valid Email',
param: 'email',
location: 'body'
},
{
value: undefined,
msg: 'Please enter a password with 6 or more characters',
param: 'password',
location: 'body'
}
]
}
Here is my signup.ejs file.
<!doctype html>
<html lang="en">
<%- include('./partials/header.ejs')%>
<%- include('./partials/navbar.ejs')%>
<body>
<section class="form my-4 mx-5">
<div class="container">
<div class="row no-gutter">
<div class="col-lg-5">
<img src="/images/joyce-busola-Nnv0DHFG1Ds-unsplash.jpg" class="img-fluid">
</div>
<div class="col-lg-7 px-5 pt-5">
<h1 class="font-weight-bold py-3">Queue's</h1>
<h4>Register your new Account</h4>
<form action="/user/register" method="POST">
<div class="form-row">
<div class="col-lg-7">
<input type="text" id="name" class="form-control my-3 p-3" placeholder="your name">
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
<input type="email" id="email" class="form-control my-3 p-3" placeholder="email address">
</div>
</div>
<div class="form-row">
<div class="col-lg-7 input-group">
<input type="password" class="form-control my-3 p-3" id="password" placeholder="password">
<div class="input-group-addon my-3 p-3">
</a><i class="bi bi-eye-slash" id="togglePassword"></i>
</div>
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
<button type="submit" class="btn1 mt-3 mb-5">Register</button>
</div>
</div>
forgot password
<p>Already have an acount? Login here</p>
</form>
</div>
</div>
</div>
</section>
<%- include('./partials/footer.ejs')%>
</body>
</html>
Here is a copy of my signup controller object.
require('dotenv').config();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { createToken } = require('../middleware/auth_middleware');
const maxAge = 36000;
module.exports.register_post = async (req, res) => {
const { name, email, password } = req.body;
// Searching if User already exists
try {
let user = await User.findOne({ email });
if(user) return res.status(400).json({ errors : [{ msg: "User already exists"}],});
// Create User Object
user = new User({ name, email, password });
// Saving new User
await user.save();
// Creating User token with JWT
let payLoad = user._id;
const prize = createToken(payLoad);
res.cookie('jwt', prize, {
httpOnly: true,
maxAge : maxAge * 1000
});
res.status(201).json({
msg: `${user.email} successfully registered`,
name: user.name,
email: user.email});
console.log(user, prize);
}
catch (error) {
console.log(error.message);
res.status(500).send('Server error')
};
}
I made a middleware to handle validations with express-validator. Here is the validator file.
require('dotenv').config()
const { check, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const maxAge = 36000;
const secret = process.env.JWT_SECRET;
const authValidator = () => {
return [
check('name', 'Please enter your name').not().isEmpty(),
check('email', 'Please enter a valid Email').trim().isEmail(),
check('password', 'Please enter a password with 6 or more characters').isLength({min:6})
]};
const validateError = (req, res, next) => {
const errors = validationResult(req);
if(errors.isEmpty()) {
return next()
}
const extractedErrors = [];
errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
console.log(errors);
return res.status(400).json({ errors: extractedErrors })
}
Here is the signup router file
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const { authValidator, validateError } = require('../middleware/auth_middleware');
router.get('/login', userController.login_get );
router.post('/login', userController.login_post );
router.get('/register', userController.register_get );
router.post('/register', authValidator(), validateError, userController.register_post );
module.exports = router;
Your input fields lack the name field. That's why the input data is not found in the body of the request.
for example for the email field:
<div class="form-row">
<div class="col-lg-7">
<input type="email" name="email" id="email" class="form-control my-3 p-3" placeholder="email address">
</div>
</div>
I am trying to validate a form in express js before i post it onto the mongodb which i am using as a backend. My user.js for registration page looks something like this -
router.post('/register', (req, res) => {
userreg.register(
// eslint-disable-next-line new-cap
new userreg({
firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.email,
usn: req.body.usn, // validate so that no space is taken or else request modal wont work
course: req.body.course,
}),
req.body.password,
(err) => {
if (err) {
console.log(err);
res.render('register', { user: 'error' });
} else {
console.log('no error');
res.render('submit-success', { username: req.body.firstname });
}
}
);
});
and my register.ejs looks something like this -
<form class="user" action = '/users/register' method="POST">
<div class="form-group row">
<div class="col-sm-6 mb-3 mb-sm-0">
<input type="text" class="form-control form-control-user" id="exampleFirstName" name="firstname" placeholder="First Name">
</div>
<div class="col-sm-6">
<input type="text" class="form-control form-control-user" id="exampleLastName" name="lastname" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<input type="email" class="form-control form-control-user" id="exampleInputEmail" name="email" placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="exampleInputUSN" name="usn" placeholder="USN">
</div>
<div class="form-group">
<select class=" form-control selectpicker" name="course">
<optgroup label="Course"></optgroup>
<option selected hidden disabled>Course</option>
<option value="mca">Computer Applications</option>
<option value="mba">Business Administration</option>
</optgroup>
</select>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-user" id="exampleInputPassword" name="password" placeholder="Password">
</div>
<div class="text-center">
<input type="submit" class = "btn btn-primary btn-user" value="Register">
</div>
</form>
By going through many sources on the internet(since i'm very very new to express js and im doing it as a part of my college project and since i can't consult any teachers for assistance during lockdown times) , I got to know that the validation part has to be implemented in user.js. Please help me with the code for validation and also displaying flash messages if field empty for atleast one field so that i can have a start atleast.
Thank you in advance
EDIT :
I Used the express-validator and ended up with the following changes -
var flash = require('connect-flash');
var app = express();
app.configure(function () {
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 } }));
app.use(flash());
});
app.get('/flash', function (req, res) {
// Set a flash message by passing the key, followed by the value, to
req.flash().
req.flash('info', 'There is an Error!')
res.redirect('/');
});
app.get('/', function (req, res) {
// Get an array of flash messages by passing the key to req.flash()
res.render('index', { messages: req.flash('info') });
});
const { check, validationResult } = require('express-validator');
router.post('/register', [
check('firstname', 'Please enter your first
name').exists().trim().escape().not().isEmpty(),
check('lastname', 'Please enter your last
name').exists().trim().not().isEmpty(),
check('username', 'Please enter an
email').exists().trim().not().isEmpty(),
check('usn', 'Please enter USN').exists().trim().not().isEmpty(),
check('course', 'Please enter Course').exists().trim().not().isEmpty(),
check('password', 'Please enter
password').exists().trim().not().isEmpty(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
req.flash('message', `${errors}`);
res.redirect('/users/register');
} else {
userreg.register(
// eslint-disable-next-line new-cap
new userreg({
firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.email,
usn: req.body.usn, // validate so that no space is taken or else
request modal wont work
course: req.body.course,
})),
res.render('submit-success', { username: req.body.firstname });
}
}
);
And as a result , the if (!errors.isEmpty()) is being invoked but there is no flash message being displayed. Am i missing something else ?
I am assuming you are using connect-flash.
const { check, validationResult } = require('express-validator');
router.post('/register', [
check('firstname', 'Please enter your first name').exists().trim().escape().not().isEmpty(),
check('lastname', 'Please enter your last name').exists().trim().not().isEmpty(),
check('email', 'Please enter an email').exists().trim().not().isEmpty(),
// ...
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
req.flash('message', `${errors}`);
res.redirect('register');
}
else {
// your code here!
}
});
You might want to consider creating middleware to handle validation errors, to make your code cleaner.
I am trying to send mail when we click the mail icon of respective id. But I am not able to send the mail.
First I click the icon, it redirects to another ejs file for sending email and then the email is sent from there. Here the mail is not sent so can anyone please help?
Thank you
mail.ejs
<form action="/send-email" method="POST">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control" placeholder="To" name="to">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="From" name="from" id="from">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Subject" name="subject" id="subject">
</div>
<div class="form-group">
<textarea class="form-control" id="content" rows="4"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="">Send</button>
</div>
</form>
Controller.js
router.get('/donation/mail/:emailid', function (req, res, next) {
res.render('mail', {email: req.query.emailid});
})
router.post('/send-email', function (req, res) {
var transport = nodemailer.createTransport(smtpTransport({
service: "gmail",
port:425,
auth: {
// should be replaced with real sender's account
user: 'xxxx#gmail.com',
pass: 'gmailpassword'
}
}));
var mailOptions = {
// should be replaced with real recipient's account
from:'xxxxx#gmail.com',
to : req.param.email,
subject : req.body.subject,
text : req.body.text
};
transport.sendMail(mailOptions, function(error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.redirect("/donation");
});
I have allowed my gmail account to access non secure app