The Resource submitted could not be validated: Mailchimp Status 400 - javascript

I have been trying to make a Simple Newsletter signup Form where I am Taking basic details from the User and sending that data to Mailchimp using API's.
I am facing the problem in sending POST HTTPS Request. Tried reading different answers but not able to solve problems.
Here's the screenshot of the Issue.
Code :
app.post("/", function (req, res) {
const firstName = req.body.fname;
const lastName = req.body.lname;
const email = req.body.email;
const data = {
members: [
{
email_address : email,
status: "subscribed",
merge_fields: {
FIRSTNAME: firstName,
LASTNAME: lastName
}
}
]
};
var jsonDATA = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/<My_LIST_ID>/members/"; //Removed List Id for now to post Question.
const options = {
method: "POST",
auth: "pranshukas:MY_API_KEY" //Removed API_KEY to post the Question
}
const request = https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
})
});
request.write(jsonDATA);
request.end();
});
I also tried using POSTMAN and there I am able to successfully send the Request to the Server and add details. But facing a Problem when I am implementing on my local server.
Please Help me out I know I am making some mistake in making post HTTPS request but stuck where.

Looks like you have some problem with the email address input, The email address field is blank and it should be populated with the email address.
Also, I think you can delete the group name(members) from the URL
const url = "https://us1.api.mailchimp.com/3.0/lists/<My_LIST_ID>/";
As recommendation i think you should add a failure route, in case of failure.
just for example:
You can make two different routes/pages for success and failure.
you can add this inside the const request anonymous function after having this routes.
if(response.statusCode === 200) {
res.sendFile(__dirname + "/success.html");
} else {
res.sendFile(__dirname + "/failure.html");
}

Related

nodeJs basic authentication issue

I'm getting no proper response while make an API request to external API using basic authentication (username and password) in nodejs (javascript)
I used the below code and the response is "undefined", not sure what is missing here.
But I was able to make a request using postman tool without any issues.
const request = require('request')
const user = '*****';
const pass = '*****!';
const url = 'https://servicenow.com/api/table'
var options = {
url: url,
auth: {
username: user,
password: pass
}
};
request.get(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(body.url);
console.log(body.explanation);
});
Response:
undefined
undefined
if your api right with postman you can do like this based on photo
send a request
click on code
select nodejs- Request
copy

How can I email links work on the front end?

I have built some functionality into my API that sends a verification email to a user and then when a get request is made to the route the user then becomes active and can be used to login. In order to make this work on the front end I have used a res.redirect which takes me to the login page.
The problem, however, is that this means that when I want to replicate this journey in postman I then receive a load of html rather than a formatted json response. So my question is, is there a way that we can handle this request so that, depending on where it is called, a different response is sent back? As I do not think an event listener will work in the case of an email.
For context, my application uses nodejs, mongodb and pug templates.
`exports.signup = catchAsync(async (req, res, next) => {
const { token } = req.params;
const { email } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findOne({ email });
if (!user || !((await user.signUpId) === token)) {
return next(new AppError('Invalid link', 401));
}
user.ready = true;
user.singUpId = undefined;
await user.save({ validateBeforeSave: false });
const url = `${req.protocol}://${req.get('host')}/me`;
await new Email(user, url).sendWelcome();
await res.redirect('http://localhost:5000/login');
});`

Express.js routing: how to prevent reloading of previous page?

I am new to express (or web development in general) and have a question about routing.
I am creating a web app on Firebase with pure JS, and am using routing on Firebase cloud functions. The routing part looks like below. The purpose is, when URL is in the form of /xxxxxx, it sends the profile html page, and when URL is for of r/xxxxx, it sends the posts html page. Then client-side rendering will be done to populate the additional data to make up a page. Below is the part of the code:
exports.webAPI = functions.https.onRequest(app);
app.get('/:id', (req, res) => {
res.set('Cache-Control', 'public, max-age=86400, s-maxage=86400');
res.status(200).sendFile(path.join(__dirname+'/app/profile.html'));
});
app.get('/r/:post', (req, res) => {
res.set('Cache-Control', 'public, max-age=86400, s-maxage=86400');
res.status(200).sendFile(path.join(__dirname+'/app/post.html'));
});
The issue is: whenever the user clicks on a post and then goes back to the profile page, the whole page is re-rendered. This is understandably very bad for user experience in the world of modern web app.
The question: how do I prevent reloading of previous page, unless there is a meaningful change to it(e.g. new post uploaded?)? Is there a way to do it in Express?
If there is a better version of code to do this, let me know . If I need to look at certain parts of the documentation, please advise. Or, if this is not possible with Express and I should look at something else, do guide me on where to look at.
Thanks!
Install axios package. In my scenario i am trying to register a form. So this all things i need to do for register without refreshing the page.
const register = async (name, email, password, passwordConfirm) => {
try {
const res = await axios({
method: "POST",
url: "your url",
data: {
name,
email,
password,
passwordConfirm
}
});
console.log(res);
if (res.data.status === "success") {
alert("You are registered succesfully");
window.setTimeout(() => {
location.assign("/");
}, 1500);
}
} catch (error) {
alert(error.response.data.message);
console.log(error);
}
};
document.querySelector("#registerform").addEventListener("submit", e => {
e.preventDefault();
const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
const passwordConfirm = document.getElementById("confirmPassword")
.value;
register(name, email, password, passwordConfirm);
});
Note: e.preventdefault plays major role.

How to resolve Can't set headers after they are sent, in express framework NodeJS?

Building first express application, bear with me...
The application has a user login, authenticating with an API.
Enter some information and post an API call, then send a text message based on data entered and the API data returned.
Upon the first login got no error, application runs successfully, text sent, user redirected back to login screen.
Upon the second login, got the following errors on the login/auth function.
Error: Can't set headers after they are sent.
TypeError: req.next is not a function
Don't see duplicate call backs, but maybe missing something, and do not have next defined in my code.
enter image description here
Here is the code where it seems to be failing...
//login page - post
app.post('/', urlencodedParser, function(req,res) {
//console.log(req.body);
username = req.body.username
password = req.body.password
//Login function / Routing to rbhGetMRN
var authEHR = function(){
console.log('AuthEHR:');
var json = buildJSON('GetUserAuthentication', Appname, username, '', token, password);
unityAction(json, function(body) {
console.log('Output from GetUserAuthentication: ');
//console.log(body);
usrData = JSON.parse(body)
var valid_user = usrData[0]['getuserauthenticationinfo'][0]['ValidUser'];
if (valid_user == 'YES') {
res.render('rbhGetMRN');
res.end();
console.log('Login Success');
}
else {
//console.log('EHR user is invalid: ' + usrData[0]['getuserauthenticationinfo'][0]['ErrorMessage']);
console.log('Login Failure');
res.render('rbhLogin');
res.end();
emitter.emit('CleanUp');
}
});
};
});
Thanks for your feedback.

Javascript scraper logging in

I seem to be doing something wrong.
I have a student website that I want to scrape, but first I need to log in. Currently I have a python scraper that does it. The website logs in with a post request to a url containing a sid and PIN.
var login_url = 'https://example.com';
var formData = {
sid: 'username',
PIN: 'password'
}
How would I go about creating the same scraper but with javascript? I have seen the request library, which seems like what I want to use but cannot get it to work.
You need to use the request module to POST the form data to your endpoint. The response from the server will be in the call back to the .post() method.
const request = require('request');
// do not reassign "request", if you need to set properties us a different variable
// use the action= value from the form for the URL
const url = 'https://central.carleton.ca/prod/twbkwbis.P_ValLoginn';
const data = {
sid: 'username',
PIN: 'password',
};
request.post({ url: url, formData: data }, (err, response, body) => {
if (err) {
console.log('failed', err);
} else {
console.log('the response', body);
}
});
If you are interesting in parsing the resulting HTML I recommend using CheerioJS - much like jQuery but server side.

Categories