Error 400 on trying to add a contact in mailchimp - node.js

I am getting this error when trying to call the mailchimp API V3 to add a new contact to my list
"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":"f8b79d9b-1c02-4062-a0e4-847e31f7bd61","errors":[{"field":"","message":"Schema describes object, NULL found instead"}]}'
Here is the code used:
app.post("/", function(req,res){
var email = req.body.email;
var data = {
members : [
{
email_address: email,
status: "subscribed"
}
]
};
var jsonData = JSON.stringify(data);
var options = {
headers :{
'Authorization': 'thomas APIKEY',
'Content-Type': 'application/json',
'Content-Length': jsonData.length
},
url: "https://us20.api.mailchimp.com/3.0/lists",
method: "POST",
data:jsonData
};
console.log(options);
request(options, function(error, response, body){
if(error)
{
console.log(error);
}
else{
console.log(response);
}
})
I tried adding /Listkey/members to my url with no success
Do you have some tips? Thank you

I found the solution, the elements passed to request were not good.
Here is the functional code:
app.post("/", function(req,res){
var email = req.body.email;
var data = {
"email_address": email,
"status" : "subscribed"
};
var options = {
"url": "https://us20.api.mailchimp.com/3.0/lists/c9b9a6e109/members/",
"method": "POST",
"headers": {
"Authorization": "thomas APIKEY"
},
"body": data,
"json": true
};
})

Related

Search Contacts with SendGrid API

https://sendgrid.api-docs.io/v3.0/contacts/search-contacts
I'm attempting to search for a contact as shown in SendGrids docs above. In the body section below I'd like to change the hard coded "andrew#gmail.com" to be a variable. Such as email = req.user.email; What is the correct way to do that? Just setting the variable and dropping in 'email' does not work.
var request = require("request");
var options = { method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers:
{ 'content-type': 'application/json',
authorization: 'Bearer SG.key' },
body: { query: 'email LIKE \'andrew#gmail.com\' AND CONTAINS(list_ids, \'6bcc2d0c-ea17-41ba-a4a1-962badsasdas1\')' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Twilio SendGrid developer evangelist here.
Try using string interpolation using back ticks (which, as an added bonus, means you don't have to escape your single quotes), like below:
const email = req.user.email;
const body = `email LIKE '${email}' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')`;
const options = {
method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers: {
'content-type': 'application/json',
authorization: 'Bearer SG.key'
},
body: { query: query },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Send post request with Axios with body and headers

I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

Node JS Request Printing nothing in console

I'm making an post call using the nodejs requests module. However, the console.log statements seems to be not working for either the error or the response.body that I am trying to get.
My POST request needs the following headers -
Accept : "application/json"
Content-Type : "application/json"
Authorization : Basic + Base64Encoded(username+password)
The post body is something like this
Body:
{
"arg_1" : "a_string_key"
, "arg_2" : "a_string"
, "arg_3" : "a_string"
, "arg_4" : "some_value"
, "arg_5" : "some_string"
, "arg_6" : "<yyyy-mm-dd>"
, "arg_7" : "<yyyy-mm-dd>"
}
My code does nothing but send a POST request and checks if the response.statusCode ==200
Here is what I am doing
var int_user = "username";
var int_pass = "password";
var encoding = "base64"
var auth = "Basic" + new Buffer(int_user + int_pass).toString(encoding);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": auth
}
var options = {
url: 'URL_I_WANT',
// method: 'POST',
headers: headers,
body : {
"arg_1": "a_string_key",
"arg_2": "a_string",
"arg_3": "a_string",
"arg_4": "some_value",
"arg_5": "some_string",
"arg_6": "<yyyy-mm-dd>",
"arg_7": "<yyyy-mm-dd>"
},
json: true
}
console.log('Before request');
request.post(options, function(error, response) {
if (error) {
console.log(error);
}
try {
if (!error && response.statusCode == 200) {
console.log(response.body);
console.log('Success');
}
} catch (error) {
console.log(error)
}
});
console.log('After request');
The code runs without any glitch and I get the before and after request console statements. However the statements inside the requests do not appear in the console, which means my request is not going through. I am not able to understand this. Shouldn't an error come if there is an issue with the request itself? Any if the request is failing, why isn't the error printed out?
This could be because your node process is auto-closed and it will exit before the async request to finishes (haven't looked into it but it might be something configurable). I've seen such set-up on repl.it for example.
To overcome this(if not configurable), you could wrap your code in an async function and use the request-promise to call await request.
var request = require('request-promise-native');
var int_user = "username";
var int_pass = "password";
var encoding = "base64"
var auth = "Basic" + new Buffer(int_user + int_pass).toString(encoding);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": auth
}
var options = {
url: 'https://google.com',
method: 'POST',
headers: headers,
body : {
"arg_1": "a_string_key",
"arg_2": "a_string",
"arg_3": "a_string",
"arg_4": "some_value",
"arg_5": "some_string",
"arg_6": "<yyyy-mm-dd>",
"arg_7": "<yyyy-mm-dd>"
},
json: true
};
console.log('Before request');
async function main() {
try {
const response = await request.post(options);
if (response.statusCode === 200) {
console.log(response.body);
console.log('Success');
process.exit();
}
console.log(`Bad statusCode:${response.statusCode}`);
}
catch (error) {
console.log(error);
}
}
main();
you can check-out the code below
a link to the code above, working on repl.it

Passing array or nested objects in body of request npm

I have to send some parameters of String type along with one array in my body.
But it throws me an error message:
First argument must be String or buffer
Here is my code:
var tokenList = JSON.parse(req.body.tokenList);
var mobParams = {
"tokens": tokenList,
"profile": "<myprofile>",
"notification": {
"title": req.body.title,
"message": req.body.text
}
};
request({
method: "POST",
url: 'https://api.ionic.io/push/notifications',
headers: {
"content-type": "application/json",
"authorization": "Bearer ********"
},
body: (mobParams)
}, function(error, response, body){
console.log('Ionic push error', error);
console.log('IOnic push res', response);
console.log('IOnic push body', body);
if(!error){
return res.send({
code: 1,
message: "success"
});
}else{
return res.send({
code: 0,
message: error
});
}
How can I pass my array inside this object to request npm?
Also, I would like to add that this implementation works pretty fine through front-end but I have separate codebase which requires me to hit multiple FCM requests i.e. in a loop. So I would be happy to have a solution as neither ionic push nor FCM push works
For the FCM push I am trying the code below :
let desktopParams = {
"notification": {
"title": 'Merchant Portal Notifications',
"body": req.body.text
// "click_action" : action
},
"to": '/topics/' + topic
};
request({
method: "POST",
json: true,
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
"content-type": "application/json",
"authorization": "key=****"
},
body: desktopParams
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
//return body;
});
you should try stringifying your tokenList & req.body.text before you join it with with the string (try to log it and post the outcome so that people will have a better idea about the objects...):
var cho = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}];
var che = {list:[{name:'john',lname:'cena'},{name:'mary',lname:'jane'}],group:'people'}
var mobParams = {
"tokens":JSON.parse(JSON.stringify(cho)),
"profile": "<myprofile>",
"notification": {
"title": "Some title",
"message":JSON.parse(JSON.stringify(che))
}
};
console.log(JSON.stringify(mobParams));//----->{"tokens":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"profile":"<myprofile>","notification":{"title":"Some title","message":{"list":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"group":"people"}}}
var arr = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}]
var js = JSON.stringify(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: "[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}]"}
var js = JSON.parse(JSON.stringify(arr));
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: Array(2)}
var js = JSON.parse(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> "SyntaxError: Unexpected identifier"

How to add a file attachment via NodeJS REST request

There's some documentation on the Jira site on how to add an attachment to an issue via a curl request here: https://confluence.atlassian.com/display/JIRAKB/How+to+attach+an+attachment+in+a+JIRA+issue+using+REST+API
This is the code that I used to successfully create an issue:
var request = require("request");
var auth = "Basic " + new Buffer("user:password").toString("base64");
var options = {
uri: 'http://domain.com/rest/api/2/issue/',
headers : {
"Authorization" : auth
},
method: 'POST',
json: {
"fields": {
"project": {
"id": "10000"
},
"summary": summary,
"description": description,
"issuetype": {
"name": "Bug"
},
"customfield_10003": {"value": value}
}
}
};
request(options, function (error, response, body) {
if (!error) {
console.log("Success");
}
});
So in order to add an attachment to a ticket with the ID of 1200, I would think I would do something like this:
var options = {
uri: 'http://domain.com/rest/api/2/issue/1200/attachment/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : nocheck
},
method: 'POST',
json: {
"fields": {
"file" : "filename.txt"
}
}
};
But have had no luck.
Edit: Getting somewhere. Here's what I've got:
var request = require('request');
var fs = require("fs");
var auth = "Basic " + new Buffer("user:password").toString("base64");
var formData = {
file: {
value: fs.createReadStream('file.txt'),
options: {
filename: 'file.txt',
contentType: 'text/plain'
}
}
};
request.post({
url:'http://domain.com/rest/api/2/issue/14000/attachments/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : "nocheck"
},
formData: formData
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
And it uploads a file called file.txt but when I look at the attachment it prints out a stack trace that starts out like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>500</status-code><stack-trace>java.lang.NullPointerException
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.mediaTypeToString(XsrfResourceFilter.java:91)
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.isXsrfable(XsrfResourceFilter.java:76)
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.filter(XsrfResourceFilter.java:54)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:277)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
You first try:
var options = {
uri: 'http://domain.com/rest/api/2/issue/1200/attachment/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : nocheck
},
method: 'POST',
json: {
"fields": {
"file" : "filename.txt"
}
}
};
will not work because as it's not supported. Check Jira attachment documentation
So, probably you need to restructure your formData object to be
var formData = {
file: fs.createReadStream('file.txt'),
};
No need for editing meta data if you don't need them. Also make sure you've got a valid stream of your file.
About stacktrace, I see stack frames related to XSRF despite adding "X-Atlassian-Token" header which doesn't make any sense for me.

Resources