as this is my first question on StackOverflow, I do hope I provide you with enough details to the problem in order to fix it. If you need any further info, don't hesitate to ask.
In short, I'm trying to create a simple signup page for a newsletter that adds subscribers to Mailchimp.
In the terminal/command-line I get this message:
{
type: 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
title: 'Invalid Resource',
status: 400,
detail: "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
instance: '4d92a5b7-20fb-4f1c-be19-fbcd6548e745',
errors: [
{
field: '',
message: 'Required fields were not provided: email_address'
}
]
}
My HTML-body looks like this:
`
<img class="mb-4" src="images/logo.png" alt="" width="172" height="172">
<h1 class="h3 mb-3 font-weight-normal">Signup to our Newsletter</h1>
<input type="text" name="fName" class="form-control top" placeholder="First Name" required autofocus>
<input type="text" name="lName" class="form-control middle" placeholder="Last Name" required>
<input type="email" name="email" class="form-control bottom" placeholder="Email" required>
<button class="btn btn-lg btn-primary btn-block btn-sign-up" type="submit">Sign me up!</button>
<p class="mt-5 mb-3 text-muted">© PB Plus 2017-2020</p>
`
This is the 'POST' part of my Javascript:
app.post("/", function(req, res) {
const firstName = req.body.fName;
const lastName = req.body.lName;
const mail = req.body.email;
const data = {
members: [{
email_adress: mail,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
var jsonData = JSON.stringify(data);
const url = "https://us4.api.mailchimp.com/3.0/lists/fae76eccaf";
const options = {
method: "POST",
auth: "xavier1:6cbb8e0a03109b3b2ef74adc0127f986-us4"
}
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
res.sendFile(__dirname + "/succes.html");
} else {
res.sendFile(__dirname + "/failure.html");
}
response.on("data", function(data) {
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
})
If anyone knows what I did wrong, please let me know! Thanks in advance.
Well, After spending many hours figuring out what's wrong, I typed email_adress instead of email_address. Problem solved.
Related
Any help appreciated. I've got an app that pulls data from google books api. From each book page, the user is able to leave a review. The path to the review is /review/${isbn Number}. Each page has a path based on the isbn. The review routes work and I'm able to make the post request through insomnia/postman with no issues, I'm just having trouble with the front-end js in pulling the data from the input boxes to make the post request. I'm not sure if the issue is because the isbn being in the path. Below is my front-end javascript that I am unable to fix.
const newFormHandler = async (event) => {
event.preventDefault();
console.log("testing")
const description = document.querySelector('#description').value;
const reviewTitle = document.querySelector('#reviewTitle').value;
const isbn = window.location.search
if (description) {
const response = await fetch(`api/review/${isbn}`, {
method: 'POST',
body: JSON.stringify({ description, reviewTitle }),
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
document.location.reload();
} else {
alert('Failed to create review');
}
}
};
document
.querySelector('.form-group')
.addEventListener('submit', newFormHandler);
My form is below:
<div class="col form-group">
<div class ="card reviewCard" style = "background-color:#fcf8f3; color: #65625e;">
<form id="blog-form">
<div>
<label for="reviewTitle">Review Title</label>
<input
value="{{title}}"
id="reviewTitle"
name="reviewtitle"
placeholder="Enter Review Title"
type="text"
required="required"
class="form-control"
data-bv-notempty="true"
data-bv-notempty-message="The title cannot be empty"
/>
</div>
<div>
<label for="review">Review</label>
<textarea
id="description"
name="review"
cols="40"
rows="10"
required="required"
class="form-control"
>{{description}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
And here is my route that works fine with insomnia, no issues.
router.get('/review/:id', async (req, res) => {
try {
const isbn13 = req.params['id'];
const reviewData = await Review.findAll({ where: {
isbn:isbn13
},
include: [
{
model: User,
attributes: ['name'],
}
]
})
const reviews = reviewData.map((review) => review.get({ plain:true}));
// console.log(isbn13);
res.render('review', {
isbn: isbn13, reviews:reviews
});
} catch (err) {
console.log(err)
}
});
Any help appreciated. I tried to pull in the isbn number from the path, but with no success. I think I have it formatted wrong somehow.
First console log your req
You should see the body containing some data.
In a get request the they are arguments in the URL.
In a Psot request they are in the body of the request.
I am trying to create simple web app to receive dog adoption applications.
I succesfully run migrations and seeds and by doing so created these two tables:
The problem is that when I try to create new application using GUI, I get the below error:
{"response":"Error in database ForeignKeyViolationError: insert into applications (doggo_name, email, name, phone) values ('Coco', 'sam.do#gmail.com', 'Sam Do', '+12345667') - ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (dog_adoption.applications, CONSTRAINT applications_doggo_id_foreign FOREIGN KEY (doggo_id) REFERENCES doggos (id))"}
This is second day I am trying to figure out what is wrong. Please see my code:
MIGRATION FILE:
exports.up = function(knex) {
return knex.schema
.createTable('doggos', (table) => {
table.increments('id').notNullable();
table.string('doggo').notNullable();
table.integer('age').notNullable();
table.string('breed').notNullable();
table.string('picture').notNullable();
})
.createTable('applications', (table) => {
table.increments('id').notNullable();
table.string('name').notNullable();
table.string('email').notNullable();
table.integer('phone').notNullable();
table.string('doggo_name').notNullable();
table.integer('doggo_id').unsigned().notNullable();
table.foreign('doggo_id').references('doggos.id');
table.dateTime('updated_at').defaultTo(knex.raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
table.dateTime('created_at').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP'));
});
};
APPLICATION seed:
exports.seed = function(knex) {
return knex('doggos').select().then(doggos => {
return knex('applications').insert([
{ name: "xxxxxxxxx", email: "peggy33#gmail.com", phone: 79187877, doggo_name: 'Coco', doggo_id: doggos.find(doggo => doggo.doggo === 'Coco').id},
{ name: "xxxxxxxxxxxxx", email: "watson.dddk#gmail.com", phone: 51393129, doggo_name: 'Tyson', doggo_id: doggos.find(doggo => doggo.doggo === 'Tyson').id},
{ name: "xxxxxxxxxxxxx", email: "ravsp33#gmail.com", phone: 12345678, doggo_name: 'Nicky', doggo_id: doggos.find(doggo => doggo.doggo === 'Nicky').id}
]);
});
};
HTML FORM:
<form action="/apply" method="POST">
<div class="application-container">
<label for="name">What is your name?</label>
<input type="text" placeholder="Your name" name="name" required>
<label for="email">E-mail address</label>
<input type="text" placeholder="e-mail" name="email" required>
<label for="phone">Phone number</label>
<input type="text" placeholder="phone" name="phone" required>
<label for="doggo_name">Name of dog you are interested with</label>
<input type="text" placeholder="Name of dog you are interested with" name="doggo_name" required>
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-primary" onclick="window.location.href='/'">Cancel</button>
</div>
</form>
</body>
ROUTE:
router.post('/apply', async (req,res) => {
const { name, email, phone, doggo_name } = req.body;
console.log(name, email, phone, doggo_name);
try {
const submittedApplication = await Application.query().insert({
name,
email,
phone,
doggo_name,
// how to pass doggo_id to the database?
});
return res.send({ response: `Succesfully applied for adoption. Please wait patiently for our response!`});
} catch (error) {
return res.send({ response: "Error in database " + error });
}
});
I would really appreciate if somebody could look at it with a fresh eye nd give me a hand with data persistence to my 'applications' table.
You make the doggo_id not nullable, so it will get 0 as default for all existing rows instead of NULL.
But then you also set it as foreign key to doggos.id. The foreign key constraint immediately fails on all rows since they would now all reference the doggo with ID 0 which presumably doesn't exist.
You can solve that problem by making it nullable (remove notNullable() from doggo_id), which works because NULL means "not referencing anything at the moment" (as opposed to "referencing the doggo with ID zero"), or by setting a default of an ID that belongs to an actually existing doggo and not zero, if that makes sense in your use case.
When signing up a user, I get no error what so ever, the signup works, but it doesn't create a new DB collection with the signup email.
Furthermore, redirecting the user to /account/dashboard.html doesn't work.
Any ideas? I am very new to all of this, only 4 days in so if you could please explain things a little simpler to me that would be very much appreciated.
// sign up the user
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred => {
return db.collection('users').doc(cred.user.uid).set({
email: "signupForm['signupEmail'].value"
});
}).then(function() {
window.location.replace('/account/dashboard.html');
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log('Error code: ' + errorCode);
console.log('Error message: ' + errorMessage);
signupButton.style.display = 'flex';
signupError.innerText = errorMessage;
signupError.style.display = 'flex';
signupForm.reset();
});
})
// Trigger button click on enter
var input = document.getElementById("signupPasswordConfirm");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Trigger the button element with a click
document.getElementById("signupButton").click();
}
});
My HTML
<div class="form-content"><label for="signupPassword-2" id="signupError" class="error-message">Error message</label>
<div class="form-wrap extra-space"><input type="text" class="text-field w-input" maxlength="256" name="signupEmail" data-name="signupEmail" placeholder="E-mail" id="signupEmail"></div>
<div class="form-wrap extra-space"><input type="password" class="text-field w-input" maxlength="256" name="signupPassword" data-name="signupPassword" placeholder="Password" id="signupPassword"></div>
<div class="form-wrap extra-space"><input type="password" class="text-field w-input" maxlength="256" name="signupPasswordConfirm" data-name="signupPasswordConfirm" placeholder="Confirm your Password" id="signupPasswordConfirm"></div>
<div class="button-wrap"><a id="signupButton" href="#" class="button w-button">Signup</a>
<h5 class="h5 black centered">Already have an account?</h5>
</div>
Turns out I forgot to declare the DB variable. Also changed the output of email:
// sign up the user
const db = firebase.firestore();
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred => {
return db.collection('users').doc(cred.user.uid).set({
email: signupForm['signupEmail'].value
});
I have been trying to set up nodemailer with my static site. I am having trouble getting require to work at the moment. I know I am doing something wrong - I just need another set of eyes to assist.
HTML:
<form name="betaForm" action="/betaForm" method="post">
<div class="form-group" >
<label for="contactName" style="float:left;">Contact Name</label>
<input type="test" name="contactName" value="" class="form-control" id="contactName" >
</div>
<div class="form-group">
<label for="practiceName" style="float:left;">Practice Name</label>
<input type="test" name="practiceName" value="" class="form-control" id="practiceName">
</div>
<div class="form-group">
<label for="phone1" style="float:left;">Phone</label>
<input type="test" name="phone1" value="" class="form-control" id="phone1">
</div>
<div class="form-group">
<label for="email1" style="float:left;">Email</label>
<input type="email" name="email1" value="" class="form-control" id="email1" >
</div>
<button type="submit" value="Send" class="btn btn-default">Submit</button>
</form>
SERVER.JS
var express=require('express');
var nodemailer = require("nodemailer");
var app = express();
app.get('/',function(req,res){
res.sendfile('www/index.html');
});
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});
SENDMAIL.JS
var app = require('express');
var nodemailer = require('nodemailer');
app.get('/betaForm', routes.betaForm);
app.post('/betaForm', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "test#gmail.com",
pass: "password"
}
});
//Mail options
mailOpts = {
from: req.body.contactName + ' <' + req.body.email1 + '>', //grab form data from the request body object
to: 'test#gmail.com',
subject: ' beta contact form',
text: req.body.contactName,
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.render('betaForm', { title: ' beta contact', msg: 'Error occured, message not sent.', err: true, page: 'contact' })
}
//Yay!! Email sent
else {
res.render('betaForm', { title: ' beta contact', msg: 'Message sent! Thank you.', err: false, page: 'contact' })
}
});
});
ROUTES.JS
var exports = module.exports = {};
exports.betaForm = function(req, res){
res.render('betaForm', { title: 'beta contact form', page: '/#beta' })
};
Sorry I'm not allowed to write comments.
Do you use the bodyparser?
In my application, i have a html form to add user. Once user is added they will get mail using sendmail() function in javascript. Everything works fine and mail is sending as my standard. But i want to add the user name in the content of my email message.
example:
DEAR {USERNAME}
(follwed by my message)
HTML form is:
<form id="frmAddUser" method="post" action="/add_value" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="focusedInput">First Name</label>
<div class="controls">
<input class="input-xlarge focused" name="txtFirstName" type="text" id="txtFirstName" tabindex="2">
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">Last Name</label>
<div class="controls">
<input class="input-xlarge focused" name="txtLastName" type="text" id="txtLastName" tabindex="3">
</div>
</div>
<div class="form-actions">
<input id="btnSubmit" class="btn btn-primary" value="Add User" onclick="return validateControls(this.form);" type="submit" />
<input id="btnCancel" class="btn" value="Clear" onclick="document.getElementById('tsubmit').style.display='none'; document.getElementById('loadeux').style.display=''; return true;" type="submit" />
</div>
</form>
And my js is like this:
exports.InsertData = function (req, res) {
var timestamp = new Date();
console.log(timestamp);
obj._id = req.body.txtLoginId,
obj.name = { f: req.body.txtFirstName, l: req.body.txtLastName },
obj.email = req.body.txtEmailID,
obj.MobileNo = req.body.txtmobile,
obj.Phone_Ext = req.body.txtphone,
obj.status = req.body.ddSfk,
obj.isAdmin = req.body.ddlAdmin,
obj.pwd = generatePassword(8),
obj.ispwdChange = "False",
obj.stamps = {
ins: timestamp,
Ins_Ip: ipAddress()
},
qry.insert(obj.schUserData, obj, function (err, result) {
if (err)
return;
sendMail(result.email, DbConfig.mailConfig.subject,'Dear{{{user}}}, Welcome to Bigtree Entertainment Pvt Ltd, Your Login details are below: your user name is: {{{user}}} and Password is: '+ result.pwd)
});
res.redirect('/Group');
}
///*----------- User Send Mail ---------------*/
function sendMail(toMailId, subject, body) {
for (var i = 0; i < 1; i++) {
email.send({
ssl: true,
host: DbConfig.mailConfig.host, // smtp server hostname
port: DbConfig.mailConfig.port, // smtp server port
domain: DbConfig.mailConfig.domain, // domain used by client to identify itself to server
to: toMailId,
from: DbConfig.mailConfig.from,
subject: subject,
reply_to: DbConfig.mailConfig.reply_to,
body: body,
authentication: DbConfig.mailConfig.authentication, // auth login is supported; anything else is no auth
username: DbConfig.mailConfig.username, // username
password: DbConfig.mailConfig.password, // password
debug: DbConfig.mailConfig.debug // log level per message
},
function (err, result) {
if (err) { console.log(err); }
});
}
}
My Json is:
{
"mongodbUrl":"mongodb://sfk:sfk#192.168.3.115:27017/BMS",
"mailConfig" :{
"host": "smtp.gmail.com",
"port": 465,
"domain": "[127.0.0.1]",
"from":"example#gmail.com" ,
"subject":"Please Use this Onetime password to create your own password",
"reply_to": "example#gmail.com",
"authentication": "login",
"username": "example#gmail.com",
"password": "paswd",
"debug": true
}
}