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.
Related
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)
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.
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);
}
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]);
});
I would like NodeJS server, post.js file, to send the json object from the AJAX request to an email using only pure NodeJS.
The following is the front-end code that sends the AJAX request:
$(document).ready(function() {
$("#contact").submit(function () {
var data = {};
$.each($(this).serializeArray(), function (key, value) {
data[value.name] = value.value;
});
data.interest = [data.interest1, data.interest2, data.interest3];
delete data.interest1;
delete data.interest2;
delete data.interest3;
console.log(data);
$.ajax({
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
url: "post.js",
success: function (data) {
$("#contact").addClass('success');
},
error: function () {
$("#contact").addClass('error');
}
});
return false;
});
});
Nodemailer offers a great way to have your node.js server send emails with easy setup. With this you can set up a simple node server such as:
//untested node.js code only for reference.
var express = require('express')
var app = express();
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var transporter = nodemailer.createTransport('TODO: setup your SMTP');
app.post('/', function (req, res) {
var mailOptions = {
from: "TODO: sender",
to: "TODO: recipient",
text: req.body
}
app.listen('TODO: some port');
Check nodemailer's documentation for details on setting up the server to suit your needs.