Why is node.js not generating an email with guerrillamail? - javascript

I am writing code that creates an email address with guerrillamail.
But, the code I created below:
var request = require('request');
var jar = request.jar();
request({
uri: 'http://api.guerrillamail.com/ajax.php',
method: 'GET',
proxy: proxy,
jar: jar,
form: {
"f": "get_email_address"
}
}, function(e, response, b) {
console.log(b);
});
Only logs :
ERR_INVALID_REQ
In body when I log it. How can I get this to work?

probably need a POST request not GET try changing the method

Related

How curl maps onto Google App Script URLFetchApp

I'm looking to implement Stripe in Google Apps Script, which comes with a URLFetch feature for communicating with third parties. However, I'm confused how the curl format that Stripe uses maps onto URLFetch.
Here's an example of a Stripe call from their documentation:
curl https://api.stripe.com/v1/charges \
-u testtoken123: \
-H "Idempotency-Key: testkey" \
-d amount=2000 \
-d currency=usd \
-d description="Charge for jenny.rosen#example.com" \
-d source=tok_mastercard
And the URLFetchApp documentation is here: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Do the flags in the curl call map directly to params in URLFetch?
Below is an example of helper functions that can be used to call the Stripe API in Google Apps Script.
function getAuthHeader(){
var apiKey = "STRIPE_API_KEY__CONSIDER_TO_GENERATE_A_KEY_WITH_LIMITED_SCOPE";
var authHeader = 'Basic ' +Utilities.base64Encode(apiKey);
return {
headers: {Authorization: authHeader}
}
}
function goFetch(url){
var reponse;
try{
reponse = JSON.parse(UrlFetchApp.fetch(url,getAuthHeader()).getContentText());
}catch(err){
Logger.log(err);
}
return reponse;
}
Example usage, listing charges:
function listCharges(lim){
var url = 'https://api.stripe.com/v1/charges?'+limit=lim;
return goFetch(url);
}
Logger.log(listCharges(10));
In your example, you are making a post request with curl. From the curl manual:
-d, --data
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit
button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.
In the UrlFetchApp reference manual you find the following:
// Make a POST request with form data.
var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
'name': 'Bob Smith',
'email': 'bob#example.com',
'resume': resumeBlob
};
// Because payload is a JavaScript object, it will be interpreted as
// as form data. (No need to specify contentType; it will automatically
// default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options = {
'method' : 'post',
'payload' : formData
};
UrlFetchApp.fetch('https://httpbin.org/post', options);
So a goPost function would be something like this:
function goPost(url,data){
var options = {
'method' : 'post',
'payload' : data,
'headers': getAuthHeader()['headers']
};
var response;
try{
response = JSON.parse(UrlFetchApp.fetch(url,options).getContentText());
}catch(err){
Logger.log(err);
}
return response;
}
Example usage:
var data = {
amount: 2000,
currency: 'usd',
source: 'tok_amex',
description: 'Charge for jenny.rosen#example.com'
}
var result = goPost('https://api.stripe.com/v1/charges',data);
Logger.log(result);

Express.js http call inside route doesn't update variable

I'm building a REST api on top of express.js. I am having trouble updating variables inside my routes.
Example:
I'm calling app.get("/wp/page/create/:id", function(req, res)
Inside this route I start by calling a http request using request-promise library. The response of this call I use in a nested http call.
I use a global variable for the headers for the nested call, and it's to the header a i need to make changes by using the etag variable.
Code:
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
res.send(data).end()
console.log("All done!");
})
})
When i start the server up and enter the route everything works fine. When i when try to hit it again the etag variables is still the same, even though it should be updated.
If I restart the server it works the again on the first attempt but fails on the second/third.
Any idea what I am doing wrong?
I have resolved the issues. The simple solution was to clear the headers containing the variable.
global.postHeaders = headers;
postHeaders['X-HTTP-Method'] = "MERGE";
postHeaders['Content-Type'] = 'application/json;odata=verbose';
postHeaders['X-RequestDigest'] = spContext;
request.get({
url: "xxx",
headers: headers,
json: true
}).then(function(response) {
var etag = response.d.__metadata.etag
postHeaders['If-Match'] = etag;
request.post({
url: "xxx",
type: "POST",
body: data,
headers: postHeaders,
json: true
}).then(function(data) {
postHeaders['If-Match'] = "";
res.send(data).end()
console.log("All done!");
})
})
postHeaders is a global variable. is headers in global.postHeaders = headers; also a global varaible ? Whatever you are trying to do here is grossly wrong. postHeaders variable will be shared across multiple request. so you will hit a scenario where postHeaders['If-Match'] value might be empty string or the etag .
Try this instead of the first line
var postHeaders = Object.assign({}, headers);
Not sure what you are trying, but at-least this statement will subside the huge error in the code. This will create a new header object for each request.

HTTPS request not posting body of REST request

I'm trying to POST to an API endpoint on my server. I know my endpoint works because if I use Advanced REST Client, I can hit it and get a JSON response as expected. The problem seems to be that no data is being sent in the body of my request despite calling request.write(postData) which contains a key, value pair. Without this data being sent in the body, my server returns a 401 error as expected without this information. Printing out the content of the POST server-side is empty but I'm clueless as to why it's empty.
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
I have testing you code again httpbin.org/post and it seems that it is working.
I believe that the issue related to, that your should POST application/json and not "application/x-www-form-urlencoded
Please try to change the header
headers: {
"Content-Type": "application/json"
}
Then, try to change the postData to JSON string:
var postData=JSON.stringify({access_token:"xxxxx"})
To be sure that problem you success to send and the problem is not local (maybe there is an issue in your server), change the target to mirror URL:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
If there is no problem in your NodeJS version, the is the response you should get: (It is mean that the server got the posted data)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
BTW: I really recommend you to move to a library to manage the request for you:
https://github.com/request/request - Very popular
https://github.com/request/request-promise - For popular who like to use the Promise syntax (The next thing in JavaScript)
https://github.com/visionmedia/superagent - For people who like to write same code in Browser & Server

"JSON_PARSING_ERROR: Unexpected character (d) at position 0." when sending GCM request from GAS

This seems very similar to a number of other questions and it seems obvious that the error indicates there's something wrong with my JSON payload. But I'm at a loss as to why.
I'm running a Google Apps Script to test sending a message to Google Firebase Cloud Messaging.
My code:
function SendGCMessage() {
var url = "https://gcm-http.googleapis.com/gcm/send";
var apiKey = "AbCdEfG";
var to = "ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"
var payload = {
"data": {
"message" : "This is the message"
},
"to":to
};
var sendCount = 1;
var headers = {
"Content-Type": "application/json",
"Authorization": "key=" + apiKey
};
var params = {
headers: headers,
method: "post",
payload: payload
};
var response = UrlFetchApp.fetch(url, params);
return {message: "send completed: " + response.getContentText()};
}
When I run this in debug mode, the object payload looks fine - like a normal Javascript object. params as well. UrlFetchApp takes a Javascript object, not a String in JSON notation. However I did try "JSON.stringify(params)" and I got an error. What did I do wrong?
Note: params looks like this when I pause it in the debugger:
{"headers":{"Content-Type":"application/json","Authorization":"key=AbCdEfG"},"method":"post","payload":{"data":{"message":"This
is the message"},"to":"ZyXwVuT:ToKeNtOkEnToKeNtOkEnToKeNtOkEn"}}
I discovered the problem, thanks to https://stackoverflow.com/a/10894233/3576831
the 'payload' parameter must be a string as specified here:
https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.
Adjusting this section of the script works:
var params = {
headers: headers,
method: "post",
payload: JSON.stringify(payload)
};

Sinon js call for PUT or POST methods

I am using sinon js in my project for fake server call. Its working fine for GET calls but I have a scenario in which I want to mock a server with PUT or POST call.
I am doing it in this way:
server = sinon.fakeServer.create();
server.respondWith('PUT', /\/administration\/email/,
[204, { "Content-Type": "application/json" }, JSON.stringify(EmailModelFixture)]);
emailView.save("abc#gmail.com");
server.respond();// Responding that save call.
But this is not working. Any one know how to fix it?
I've checked this scenario and it looks ok to me, so it works well.
Here is an example for Backbone
test("should submit PUT request", function() {
var server = sinon.fakeServer.create();
server.respondWith('PUT', /\/administration\/email/,
[204, { "Content-Type": "application/json" }, JSON.stringify({a:"1"})]);
var spy_done = sinon.spy();
var spy_fail = sinon.spy();
var model = new (Backbone.Model.extend({
url: "/administration/email/"
}));
// Save new model to generate PUT request
model.save({ id: "test" }, {
success: spy_done,
error: spy_fail
});
server.respond();
expect(spy_done.called).to.be.true;
expect(spy_fail.called).to.be.false;
});
I'd recommend you to debug your ajax requests by dumping server.requests and check for url and method there to understand what's wrong.

Categories