Cant get ajax form data to submit with nodemailer - javascript

Good Morning Everyone,
I have made a web app using node.js and express. I got Nodemailer to send an email and my AJAX is sending the parsed JSON data to express, but I am having trouble getting that from data into nodemailer. My Ajax is sending the JSON to express I have confirmed that with DEV Tools, but I'm at a loss on how to put the JSON into nodemailer. Any help would be much appreciated.
/* contact Route: contact.js */
var express = require('express');
const contact = express.Router();
var path = require('path');
const bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
contact.use(bodyParser.json() );
contact.use(express.static(__dirname + 'portfolio'));
contact.get('/contact', (req,res,next) => {
res.sendFile(path.join(__dirname, '../html-files', 'contact.html'));
console.log('this works');
});
contact.post('/contact', (req,res) => {
/*const data = req.body.data;
const from = data.email;
const text = data.message;*/
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'augustshah#02pilot.com',
pass: 'hgahalzecelxdxis'
}
});
var mailOptions = {
from: this.email,
to: 'augustshah#02pilot.com',
subject: 'Quote',
text: this.message
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
})
module.exports = contact;
/* Jquery: script.js*/
//const { json } = require("body-parser");
//var requirejs = require('requirejs');
//const { json } = require("body-parser");
$('#submit').on('click', function(e) {
e.preventDefault();
const name = $("#name").val();
const email = $("#email").val();
const message = $("#message").val();
var $form = $( this ),
url = $form.attr( "action", "/contact");
const data = {
name: name,
email: email,
message: message
};
$.ajax({
type: "POST", // HTTP method POST or GET
url: "/contact", //Where to make Ajax calls
dataType: "json", // Data type, HTML, json etc.
data: JSON.stringify(data), //Form variables
success: function() {
alert("Your Email has been sent");
},
error: function() {
alert("Your Email has not sent. Try Again. ");
}
})
});

FIXED: It was simple. in my script.js, I didn't have my contentType set. I set it to 'application/json' and that fixed my issue.

Related

How to solve TypeError: request.write is not a function

I am trying to make a newsLetter service using NodeJS & Express by using mailchimp API on hyper shell. I have installed all necessary things including npm,express,request,https module. The code works fine untill when i try to write the user Information in the mailChimp server and showing me the typeError message: request.write() is not a function. Below is my code & the snap of my errorCode.
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function (req, res) {
const firstName = req.body.fname;
const lastName = req.body.lname;
const email = req.body.email;
const password = req.body.pass;
const cPassword = req.body.cPass;
//console.log(firstName);
//res.send(firstName);
var data = {
members: [
{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}
]
};
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/97d15bb1ff";
const options = {
method: "POST",
auth: "Mr.M:d2f2f965b9e6b751a305bb6ce2ad7ed4-us1",
};
https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
//res.send("hey")
});
app.listen(3000, function () {
console.log("Server is running at port 3000");
});
Error Message Picture
res.write(jsonData)
res.end()
use above code instead of request.write(jsonData), request.end().
https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
}); });
instead use this:
const request = https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
});
As already specified by Lingyu Kong, you need to save your request in a constant variable that will allow you to call upon it later:
The node.js website link below illustrates this perfectly:
https://nodejs.org/api/http.html#http_http_request_url_options_callback
You should have saved the ClientRequest into a variable called request, and after that, you could do the write and end.
Like that :
const request = https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
You forgot to put in
const request = https.request(url, options, function(response) {
response.on("data", function(data) {
console.log(JSON.parse(data));
replace the code below:
https.request(url, options, function(response)
with this code:
const request = https.request(url, options, function(response)

While sending routes and data to server side from client . I'm not recieving data on server side

I'm trying to upload the file to server. currently I'm uploading images.
This is my client side code
onClickfileupload(){
let data={};
let path="";
let api_url = '/api/uploadFileFromIonicHome';
this.fileChooser.open()
.then(uri =>
{
path= JSON.stringify(uri);
alert(path);
data={
userEmail: this.userEmail,
userName: this.userName,
userRole: this.userRole,
fileComment: this.desc,
type: "file",
fullFileName:'file-'+Date.now()+'.jpg'
}
this.imagesProvider.uploadImage(path, data, api_url).then((res) => {
let dataPassedBackObj = {
reload: true,
pathOfFile: path,
typeOf: "picture",
userName: this.userName,
fileComment: this.desc
}
alert("Successfully uploaded picture...");
this.events.publish('toggleMenu');
}, err => {
alert(err.http_status);
alert("There was error in uploading picture...");
}); })
.catch(e => alert(e));
}
This is my provider what I'm using to upload the file to server side.
This is my providers code
uploadImage(img, data ,api_url) {
alert("Uploading file...");
// Destination URL
let url = SERVER_HOST + api_url;
// File for Upload
var targetPath = img;
console.log("line 28"+targetPath);
var options: FileUploadOptions = {
fileKey: 'image',
chunkedMode: false,
mimeType: 'multipart/form-data',
params: data,
};
const fileTransfer: FileTransferObject = this.transfer.create();
return fileTransfer.upload(targetPath, url, options);
}
This is my server side code where I'm getting the routes. but req. body is coming empty {}.
This is part of my server side code
app.post('/api/uploadFileFromIonicHome', uploadFromHome.single('image'), function(req, res) {
console.log('within /api/uploadFileFromIonicHome');
console.log(req.body.type);
console.log(req.body);
var userName = req.body.userName;
var userEmail = req.body.userEmail;
var userType = req.body.userRole;
var fileName = req.body.fileName;
var type = req.body.type;
var comment = req.body.comment;
var fileComment = req.body.fileComment;
I'm getting empty "req.body"
and "req.body.type is undefined."
This the error I'm getting
typeerror:cannot convert object to primitive value
Use connect-multiparty to read files. Reference link
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload', multipartMiddleware, function(req, resp) {
console.log(req.body, req.files);
// don't forget to delete all req.files when done
});

Ajax request keeps failing with bad request when Postman works

So I have been researching for hours and trying different things and have been researching for hours to no avail. The call is to get a JWT token after providing user and pass.
function listenForLogin() {
console.log('listening')
$('#submit-btn').on('click', e => {
e.preventDefault();
console.log('button-pressed');
const username = $('#user-input').val().trim();
const password = $('#pass-input').val().trim();
var user = {}
user.username = username;
user.password = password
console.log(user);
$('#user-input').val('');
$('#pass-input').val('');
authenticateUser(user);
});
}
//send to autenticate
function authenticateUser(user) {
console.log('trying to authenticate');
const settings = {
url:"/api/auth/login",
data: JSON.stringify(user),
dataType: "json",
method:"POST",
success: (data) => {
console.log('authenticated user');
redirectWithToken(data.authToken, user);
},
error: (err) => console.log(err)
}
$.ajax(settings);
}
When it hits the server morgan sees that there was a request but i get back a status of 400. here is my routes
'use strict';
const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const {JWT_SECRET, JWT_EXPIRY} = require('dotenv').config();
const router = express.Router();
const createAuthToken = function(user) {
return jwt.sign({user}, 'shade', {
subject: user.username,
expiresIn: '7d',
algorithm: 'HS256'
});
};
const localAuth = passport.authenticate('local', {session: false});
router.use(bodyParser.json());
router.post('/login', localAuth, (req, res) => {
const authToken = createAuthToken(req.user.serialize());
res.json({authToken});
});
const jwtAuth = passport.authenticate('jwt', {session: false});
router.post('/refresh', jwtAuth, (req, res) => {
console.log('refresh targeted');
const authToken = createAuthToken(req.user);
res.json({authToken});
});
router.get('/dashboard/:user', jwtAuth, (req, res) => {
res.redirect(`https:flow-state.herokuapp.com/dashboard/${req.params.user}`);
})
module.exports = router;
and I am having a hard time understanding how passport.authenticate('localAuth') works so here is my strategies file just in case you need that
Update: I am getting some kind of error when checking the requests on fiddler.
RESPONSE BYTES (by Content-Type)
~headers~: 132
~???????~: 11
anybody got any clue what that means?
Did you miss the content-type in the ajax settings?
Add contentType: "application/json" in the ajax settings and try again.
Note :
dataType defines the data type expected of the server response.
contentType defines the data type of the content which will be sent to the server. Default is: "application/x-www-form-urlencoded"
8 hours later and a big headache a solution is here. #vignz.pie you were right but I needed to send the 'Content-Type': 'application/json' in the headers along with strigify the data setting the processData: false did the trick. Thanks for the help!
function listenForLogin() {
console.log('listening')
$('#submit-btn').on('click', e => {
e.preventDefault();
console.log('button-pressed');
const username = $('#user-input').val().trim();
const password = $('#pass-input').val().trim();
$('#user-input').val('');
$('#pass-input').val('');
authenticateUser(username, password);
});
}
//send to autenticate
function authenticateUser(user, pass) {
var info = {
username: user,
password: pass
};
console.log(info)
const settings = {
url:"/api/auth/login",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify(info),
processData: false,
dataType: "json",
method:"POST",
success: (data) => {
console.log('authenticated user');
redirectWithToken(data.authToken, user);
},
error: (err) => console.log(err)
}
$.ajax(settings);
}

Jquery ajax request response 404 when make a post request

I am creating a basic friend request feature. This is one of the function I am working on, when Ajax send the post request it shows 404. It works if I put the code directly in the server.js file but I am trying to organize the code. Any solution? Thanks!
client.pug make a ajax request when user add friend by using email and hit submit
$('#addFriend').on('click', function(ev) {
ev.preventDefault();
var searchByEmail = $('#searchByEmail').val();
$.ajax({
type: 'POST',
url: '/add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
email: searchByEmail
},
success: function(data) {
console.log('success');
}
});
document.getElementById("searchByEmail").value = "";
$('#userModal').modal('hide'); });
controllers/friend.js
const express = require('express');
const app = express();
const User = require('../models/user');
const bodyParser = require('body-parser');
var friendRequest = function() {
app.post('/add', function(req, res) {
var requestToEmail = req.body.email;
console.log(requestToEmail);
User.findOne({
email: requestToEmail
}, function(err, email) {
if (!email) {
console.log('cannot find the email', err);
return res.send(err);
}
/*
Add into database
Display the friend list
*/
})
});
} // End friend request
module.exports = friendRequest;
server.js include and use the module
const friendInvite = require('./controllers/friend');
app.use('/friend', friendInvite);
file structure
- server.js
- controllers
- friend.js
- views
- client.pug
Try change your code on controllers/friend.js like below :
const express = require('express');
const app = express();
const User = require('../models/user');
const bodyParser = require('body-parser');
var friendRequest = function() {
app.post('/add', function(req, res) {
var requestToEmail = req.body.email;
console.log(requestToEmail);
User.findOne({
email: requestToEmail
}, function(err, email) {
if (!email) {
console.log('cannot find the email', err);
return res.send(err);
}
/*
Add into database
Display the friend list
*/
//add this response to client side
res.json({ 'status': '200', 'desc': 'Success' });
})
});
} // End friend request
module.exports = friendRequest;
you must send response to client side what is sign if the data has saved.
maybe you can try to check snippets code here :
https://github.com/egin10/node_mongoose/blob/master/routes/student.js
I didn't see response in your app.post()
So it will be 404(Not found).
When you find a User, you can response something.
For example, a 'success' message and friend list.
app.post('/add', function(req, res) {
res.json(['success', friend list]);
});

Ajax post 404 on POST

I am trying to send a test email using node.
My server code index.js looks like this:
var http = require("http"),
express = require('express'),
nodemailer = require('nodemailer'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.post('/contact', function (req, res) {
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
var mailOpts, smtpTrans;
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "email#gmail.com",
pass: "password"
}
});
mailOpts = {
from: name + ' <' + email + '>', //grab form data from the request body object
to: 'cmatsoukis#gmail.com',
subject: "Website Contact",
text: message
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.send(false);
}
//Yay!! Email sent
else {
res.send(true);
}
});
});
app.listen(1337, '127.0.0.2');
This is my ajax code when I submit the form
var form = $("form#contact_form");
form.submit(function () {
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var msg = $('#message').val();
var info = {"name" : name, "email": email, "message" : msg}
$.ajax({
url: 'http://127.0.0.2:1337',
type: 'POST',
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
jsonpCallback: 'callback', // this is not relevant to the POST anymore
//dataType: 'json',
success: function (data) {
MailSuccess()
lightSpeed();
},
error: function () {
MailFail();
}
});
});
I am getting the error POST http://127.0.0.2:1337/ 404 (Not Found)
I do not think I have the url correct. I have app.post('/contact', function (req, res) { But I do not this that is correct. And shouldn't I put a file name in the url: 'http://127.0.0.2:1337',?
I believe I have everything else correct. Please let me know.
You've registered a POST handler for '/contact' but you are making the request to '/'.
Since you haven't told express what to do for '/' it returns a Not Found.
Make the two paths match.

Categories

Resources