The following code in my server successfully sends an email when a submit button is hit on the splash page. I am pulling a list that is input from the user coming from mongoDB. When I call console.log on the variable data it shows that everything is in it's right place. This is what I get in the terminal, followed by the code itself. The problem is that everything looks correct except the emails are blank in the body. Subject is there but everything that the console is printing out in html through ejs is gone. Terminal says its there but when I receive email, blank...
DB CONNECTION SUCCESSFUL
Monday, March 21
Server is Flying
html data ======================> <body>
<h1></h1>
<ul>
<li>Welcome to Fedex Staffing Beta!</li>
<li>Geoffrey Singfred</li>
<li>Elizabeth Holmes</li>
<li>Diana Ross</li>
<li>Frank</li>
</ul>
</body>
[Error: 31772:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:
] {
library: 'SSL routines',
function: 'ssl3_get_record',
reason: 'wrong version number',
code: 'ESOCKET',
command: 'CONN'
const express = require("express");
const ejs = require("ejs");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
const date = require(__dirname + "/date.js");
const nodemailer = require("nodemailer");
// MONGO CONNECTION //
// This is the connection to the database. 27017 is the port mongo chooses by default
mongoose.connect("mongodb+srv://user-admin:password#cluster0.zrsn0.mongodb.net/cluster0?retryWrites=true&w=majority")
console.log("DB CONNECTION SUCCESSFUL")
// EE TABLE //
// This is the employee default schema. Just a name.
const itemsSchema = new mongoose.Schema ({
item: String,
});
const listSchema = new mongoose.Schema({
name: String,
items: [itemsSchema]
});
// This initializes a new schema or what Mongo calls a collection. Each collection
// is essentially the equivalent of a table in SQL
const Item = mongoose.model("Item", itemsSchema);
const List = mongoose.model("List", listSchema);
// Write now the app starts with items by default. These are them. They can be deleted
// easily by checking the box in the app. I'm sure there is a better way to do this.
const item1 = new Item({
item: "Welcome to Fedex Staffing!",
});
// Just a default list I use to call when a new page is created.
const defaultItems = [item1];
////// BEGIN APP //////
// Intitalize date
const day = date.getDate();
// Initialize express
const app = express();
// Initialize ejs
app.set("view engine", "ejs");
app.use(express.static("public"));
// Intialize body parser.
app.use(bodyParser.urlencoded({
extended: true
}));
// MAIN PAGE //
// A GET call to retrieve all current items in the database, if there are less
// than zero then it adds back the default items listed below
app.get("/", function(req, res) {
Item.find({}, function(err, foundItems){
if (foundItems.length === 0){
Item.insertMany(defaultItems, function(err){
if (err) {
console.log(err);
} else {
console.log("Items successfully added.");
}
});
res.redirect("/");
} else {
res.render("list", {listTitle: day,newListItems: foundItems});
};
});
});
// A POST call to add items to the list and the database
app.post("/", function(req, res) {
const itemName = req.body.newItem;
const listName = req.body.list;
const item = new Item({
item: itemName
});
if (listName === day){
item.save();
res.redirect("/");
} else {
List.findOne({name: listName}, function(err, foundList){
foundList.items.push(item);
foundList.save();
res.redirect("/" + listName);
});
};
});
// This delete route for when you check a checkbox, it then deletes the item.
app.post("/delete", function(req, res){
const checkedItemId = req.body.checkbox;
const listName = req.body.listName;
if (listName === day){
Item.findByIdAndRemove(checkedItemId, function(err){
if(!err) {
console.log("Successfully deleted checked item")
res.redirect("/");
};
});
} else {
List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
if(!err){
res.redirect("/" + listName);
};
});
};
});
app.post("/send", function(req, res){
const title = req.body.customName
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 666,
secure: true, // use SSL
auth: {
user: "***********#hellmail.com",
pass: "*********"
}
});
Item.find({}, function(err, foundItems){
const data = ejs.renderFile(__dirname + "/views/emailtemp.ejs", {newListItems: foundItems, listTitle: title}, function (err, data) {
if (err) {
console.log(err);
} else {
var mainOptions = {
from: '"Jesus"*************#gmail.com',
to: "*********#gmail.com",
subject: 'Hello, world',
html: data
};
console.log("html data ======================>", mainOptions.html);
transporter.sendMail(mainOptions, function (err, info) {
if (err) {
console.log(err);
} else {
console.log('Message sent: ' + info.response);
}
});
}
});
});
});
console.log(day)
app.listen(process.env.PORT || 3000, function() {
console.log("Server is Flying");
});
```
So I answered my own question for the first time. In my code, when I initialize the transporter, I have the handshake connection on secure set to 'true'. I did some reading and found that there is something going on there not matching the handshake. Without going into a ton of detail, I changed it to 'false', instead of 'true' and for the first time, the app works perfectly.
Related
I'm trying to fetch all records from MongoDB starting with the Alphabet S but every time I try doing so, it returns nothing but []. I'm using the Params tab on Postman to do this.
The code that I have written is below as well as a snip from Postman to make the question more understandable. I'm pretty sure that the API I have written to perform this has something wrong with it.
The Model file
const mongoose = require('mongoose');
const entry = new mongoose.Schema({
name : {
type : String,
},
collegeName : {
type : String,
},
location : {
type : String,
}
});
const enter = mongoose.model("Student", entry);
module.exports = enter;
index.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const dataModel = require('./model/model');
const MongoClient = mongo.MongoClient;
const uri = "mongodb+srv://coolhack069:XzC6N7dOyUeQl8M9#cluster0.kz6v9.mongodb.net/assignment?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
app.use(express.json());
app.use(bodyParser.json());
const port = 3001;
app.get('/api/get', (req, res) => {
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = {};
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
});
})
});
app.get('/api/getStudentDetails', (req, res) => { //The API I have written to query through the Database
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = new dataModel({
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
})
});
app.post('/api/add', (req, res) => { //To add Data
const name = req.body.name;
const collegeName = req.body.collegeName;
const location = req.body.location;
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const storeData = new dataModel({
name : name,
collegeName : collegeName,
location : location
});
console.log(storeData);
collection.insertOne(storeData, function(err, result) {
res.json({
result : "Success"
});
console.log(err);
client.close();
});
})
});
app.listen(port, () => {
console.log(`Application running at http://localhost:${port}`)
})
The Screenshot from Postman
Your find condition is not correct:
const fetchedData = new dataModel({ // ???
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
??? - I guest your meaning is const fetchedData = { name: req.params.name}; - Find every document which have name is req.params.name (S - in your case). But there is no document has name is S in your collection, then it returns [].
If you want to find the documents with S as the first character of their name, you can use Regex syntax:
const query = {
name : new RegExp('^' + req.params.name, 'i'), // i - case insensitive, => /^S/i
};
collection.find(query).toArray(function(err, result) {
res.send(result);
client.close();
})
I try to catch data from Postman but "req.body" brings out an empty object for me. What can be a problem with that?
I am not that good at Node.js and Express.
I read many questions on StackOverFlow but nothing worked for me, neither session nor anything else.
I've got a file app:
/*********
* app.js file
*********/
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
module.exports = function () {
let server = express(),
create,
start;
create = (config, db) => {
// add middleware to parse the json
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
extended: false
}));
let routes = require('../routes');
// set all the server things
server.set('env', config.env);
server.set('port', config.port);
server.set('hostname', config.hostname);
//connect the database
mongoose.connect(
db.database,
{
useNewUrlParser: true,
useCreateIndex: true
}
);
// Set up routes
routes.init(server);
};
start = () => {
let hostname = server.get('hostname'),
port = server.get('port');
server.listen(port, function () {
console.log('Express server listening on - http://' + hostname + ':' + port);
});
};
return {
create: create,
start: start
};
};
Here below when I try to catch data it's empty (undefined)
my user.js service
/********
* user.js file (services/users)
********/
const express = require('express');
const User = require('../../models/user');
const getUsers = async (req, res, next) => {
try {
let users = await User.find({});
if (users.length > 0) {
return res.status(200).json({
'message': 'users fetched successfully',
'data': users
});
}
return res.status(404).json({
'code': 'BAD_REQUEST_ERROR',
'description': 'No users found in the system'
});
} catch (error) {
return res.status(500).json({
'code': 'SERVER_ERROR',
'description': 'something went wrong, Please try again'
});
}
}
const createUser = async (req, res, next) => {
try {
const {
name,
email
} = req.body;
if (name === undefined || name === '') {
return res.status(422).json({
'code': 'REQUIRED_FIELD_MISSING',
'description': 'name is required',
'field': 'name'
});
}
if (email === undefined || email === '') {
return res.status(422).json({
'code': 'REQUIRED_FIELD_MISSING',
'description': 'email is required',
'field': 'email'
});
}
let isEmailExists = await User.findOne({
"email": email
});
if (isEmailExists) {
return res.status(409).json({
'code': 'ENTITY_ALREADY_EXISTS',
'description': 'email already exists',
'field': 'email'
});
}
const temp = {
name: name,
email: email
}
let newUser = await User.create(temp);
if (newUser) {
return res.status(201).json({
'message': 'user created successfully',
'data': newUser
});
} else {
throw new Error('something went worng');
}
} catch (error) {
return res.status(500).json({
'code': 'SERVER_ERROR',
'description': 'something went wrong, Please try again'
});
}
}
module.exports = {
getUsers: getUsers,
getUserById: getUserById,
createUser: createUser,
updateUser: updateUser,
deleteUser: deleteUser
}
I would appreciate any hints and suggestions on the code
Thanks!
The req.body field will be an empty object if nothing is sent in the body. For any GET requests, if you send data to the endpoint you would send via params (i.e, [website].com?paramkey1=paramvalue1¶mkey2=paramvalue2), and the body will always be an empty object. For POST and PUT requests you will send data in the body and req.body should contain that data.
I assume you are testing the createUser function. First off, I would try console logging req.body at the top of the createUser functions in case the field names are incorrect. Also, the Postman sections where you add the Body and where you add the Params look almost identical, so you may want to try console logging req.query too and/or confirm you're in the right spot on Postman.
Hard to know without more info. You know the routes are being setup, correct? Are you getting a successful response in Postman?
const express = require('express');
const mysql = require('mysql');
const app = express();
const bodyParser = require('body-parser');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
function getConnection() {
return mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'pms_tool'
})
}
//DEL REQUEST
app.delete('/users/:kpiId', (req, res) => {
console.log('Fetching user with kpiId: ' + req.params.kpiId);
const connection = getConnection();
const Id = req.params.kpiId;
const queryString = 'DELETE FROM kpi_master WHERE kpiId = ?';
connection.query(queryString, [Id], (err, rows, fields) => {
if (err) {
console.log('Failed to query for users: ' + err);
res.sendStatus(500);
return;
}
res.end('Record has been deleted!!!');
});
});
//update kpi api
app.put("/kpi_update/:kpiId", (req, res) => {
const id = req.params.kpiId;
const name = req.body.kpiName;
const description = req.body.description;
const queryString = " UPDATE kpi_master SET kpiName = ? , description = ? WHERE kpiId = ? "
getConnection().query(queryString, [name, description, id], (err, results, fields, rows) => {
if (err) {
console.log("Not updated " + err);
res.sendStatus(500);
return
}
console.log('record updates ' + results.id)
res.send(results)
})
})
//create a new kpi
app.post('/user_create', (req, res) => {
console.log('Trying to create a new user...');
console.log('first name: ' + req.body.kpiName);
const kpiName = req.body.kpiName;
const description = req.body.description;
const queryString = 'INSERT INTO kpi_master (kpiName,description) values(?,?)';
getConnection().query(queryString, [kpiName, description], (err, results, fields) => {
if (err) {
console.log('Failed to insert new user :' + err);
res.sendStatus(500);
return;
}
console.log('Inserted a new user with id:', results.insertId);
res.end();
});
res.end();
});
app.get('/', (req, res) => {
console.log('Responding to root route');
res.send('Hello from ROOT');
});
//get kpi by single ID
app.get('/users/:kpiId', (req, res) => {
console.log('Fetching user with kpiId: ' + req.params.kpiId);
const connection = getConnection();
const userId = req.params.kpiId;
const queryString = 'SELECT * FROM kpi_master WHERE kpiId = ?';
connection.query(queryString, [userId], (err, rows, fields) => {
if (err) {
console.log('Failed to query for users: ' + err);
res.sendStatus(500);
return;
}
console.log('I think we fetched users successfully');
const users = rows.map((row) => {
return { kpiName: row.kpiName, description: row.description };
});
res.json(users);
});
// res.end()
});
//get kpi
app.get('/users', (req, res) => {
const connection = getConnection();
const queryString = 'SELECT * FROM kpi_master';
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log('Failed to query for users: ' + err);
res.sendStatus(500);
return;
}
res.json(rows);
});
});
const port = 5000;
app.listen(port, () => `Server running on port ${port}`);
It gives me the error as I've shared the image
I've made one datatable for listing records and on add we can add it through api. So now I've made api and add some records and made a file named server for api and it's working but i've called api in react form but can't able to list the api. As it shows this error...
I think your node_module for mysql is not installed in your node application. Kindly install it using
npm i mysql
and then restart your application again
Thank You.
I'm new to Node, Mongoose and to everything related to Backend. I ran into a problem recently. I couldn't figure it out as the same code in exercise files of a development course seems to be the same. Nevertheless problem still doesn't resolve. Thing I'm trying to do, coding along with the tutorials, is that I want to define a Mongoose model for comments in the Mongo database for every campground section that I have displayed on the page. I have models folder where I define models for campground and comments, a seeds.js file where I dynamically add data to campgrounds (in order for it to appear with comments instantly) and then add comments. Here is what the actual code looks like for these files:
app.js-->
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require('mongoose');
var Campground=require("./models/campground");
var seedDB = require("./seeds");
var PORT = process.env.IP || 3200;
seedDB();
mongoose.connect('mongodb://localhost/yelp_camp', { useNewUrlParser: true },
(err, res) => {
if (err) throw err;
console.log('Database online');
});
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
//schema
app.get("/", function (req, res) {
res.render("landing");
});
app.get("/campgrounds/tornike", function (req, res) {
//get all campgrounds
res.send(Campground.name);
});
app.get("/campgrounds", function (req, res) {
//get all campgrounds
Campground.find({}, function (err, camp) {
if (err) {
console.log("ERROR");
console.log(err);
} else {
res.render("index", { campgrounds: camp });
}
});
});
app.post("/campgrounds", function (req, res) {
var name = req.body.name;
var image = req.body.image;
var desc = req.body.description;
var newCampground = { name: name, image: image, description:desc };
//create new camp and save to database
Campground.create(newCampground, function (err, newlyCreated) {
if (err) {
console.log(err);
} else {
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new", function (req, res) {
res.render("new.ejs");
});
//shows more info about camp
app.get("/campgrounds/:id", function (req, res) {
//find camp with provided id
Campground.findById(req.params.id, function (err, foundCampground) {
if (err) {
console.log(err);
} else {
//render show template
res.render("show", { campground: foundCampground });
}
});
});
app.listen(PORT, process.env.IP, function () {
console.log("camp");
});
seeds.js ---->
var mongoose = require("mongoose");
var Campground = require("./models/campground");
var Comment = require("./models/comment");
var data = [
{
name: "something",
image: "image URL",
description: "blah blah bla1"
},
{
name: "something",
image: "image URL",
description: "blah blah bla2"
},
{
name: "something",
image: "image URL",
description: "blah blah bla3"
}
];
function seedDB() {
Campground.deleteMany({}, function(err) {
console.log("removed camps");
data.forEach(function(seed) {
Campground.create(seed, function(err, data) {
if (err) {
console.log(err);
} else {
console.log("added campground");
Comment.create(
{
text: "dubdabdubadah",
author: "Homer"
},
function(err, comment) {
if (err) {
console.log(err);
} else {
campground.comments.push(comment);
campground.save();
console.log("Created new comment");
}
}
);
}
});
});
});
}
module.exports = seedDB;
comment.js --->
var mongoose = require("mongoose");
var commentSchema= new mongoose.Schema({
text:String,
author:String
});
module.exports=mongoose.model("Comment", commentSchema);
campground.js ---->
var mongoose = require("mongoose");
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
module.exports = mongoose.model("Campground", campgroundSchema);
Error occurs in the seeds.js file on this line campground.comments.push(comment);
it looks like this:
[nodemon] starting `node app.js`
camp
Database online
removed camps
added campground
added campground
added campground
events.js:183
throw er; // Unhandled 'error' event
^
ReferenceError: campground is not defined
I can't actually get my head around this one as when comparing the code to the exercise files code - it is the same. The only thing I can think of is the versions of mongoose express or something else may not be relevant or some methods deprecated, but honestly no idea what's wrong. I've been trying to solve it for several days. any idea people ?
The error message is telling you that you haven't defined a variable named campground, which is correct, as you haven't.
To fix this, change data to campground in your Campground.create callback:
Campground.create(seed, function(err, campground) {
I got a 500 error and de description says: Mongoose is not defined when i call /delPost, but in the same file "post.js" the functions /addPost and /getPosts are working and use mongoose.model without problems. im a newbie and have searched a lot but can't fix that issue, hope you can help me.
routes/post.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
POST message to board (WORKING)
router.post('/addPost', function(req, res) {
if(req.body){
var post = mongoose.model('post');
var newpost = new post(req.body);
console.log(newpost);
newpost.save(function(err, newpost){
if(err) return res.send(200,{msg: 'not saved'});
})
console.log('save ok');
}
else{
res.send(200,{msg: 'no data received'});
}
});
GET messages from DB to show in HTML (WORKING)
router.get('/getPosts', function(req, res) {
var post = mongoose.model('post');
post.find(function(err, posts){
if(err) return console.log(err);
// console.log(posts);
res.send(posts);
})
});
DELETE a post (NOT WORKING)
router.post('/delPost/:rel', function(req, res){
// var mongoose = require('mongoose');
var post = moongose.model('post');
post.remove({_id: req.params.rel},function(err) {
if(err) return handleError(err);
console.log(err);
})
});
AJAX Call to /delPost route
function delPost(event){
event.preventDefault();
console.log('delpost');
var confirmation = confirm('Are you sure to delete this message?');
if(confirmation === true){
$.ajax({
type:'POST',
url: '/post/delPost/' + $(this).attr('rel')
}).done(function(response){
console.log('delete done.. ');
}).fail(function(response){
console.log('delete failed');
})
}
};