I'm trying to get the receipt but I can't!
I already set "request_receipt" in AUTHORIZATIONS on my app and nothing change.
What I have to do to get de receipt?
<script>
var headers = {
'Accept-Language':'en_US',
'Content-Type':'application/json'
};
function callback(error, response, body) {
if(error){
console.log(error);
}else if (response.statusCode == 200) {
var jsonBody = JSON.parse(body);
headers['Authorization'] = `Bearer ${jsonBody.access_token}`;
getUserHistory(req,res);
}
}
request.post(options, callback);
});
function getUserHistory(req,res){
var options = {
url: 'https://api.uber.com/v1.2/history',
headers:headers
};
request.get(options, (error, response, body) => {
if(error){
console.log(error);
}else if (response.statusCode == 200) {
var bodyJson = JSON.parse(body);
bodyJson.history.map(function(model){
var options = {
url: 'https://api.uber.com/v1.2/requests/'+model.request_id+'/receipt',
headers:headers
};
request.get(options, (error, response, body) => {
if(error){
console.log(error);
}else if (response.statusCode == 200) {
res.send(body);
}
});
})
}
});
}
</script>
Running this code, I can see this message:
Related
I simply want to verify a reCAPTCHA using NodeJS and am having trouble making the simple call!
I keep getting errors missing-input-response and missing-input-secret.
Attempt 1 using request:
var request = require('request');
...
request.post(
'https://www.google.com/recaptcha/api/siteverify',
{
secret: 'MY_SECRET',
response: recaptcha
},
function (error, response, body) {
// guard
if (error) {
callback(false);
return;
}
if (response.statusCode == 200) {
console.log("BODY", body)
if (body.success) {
callback(true);
} else {
callback(false);
}
}
}
Attempt 2 using https:
var post_req;
var requestBody = {
secret: 'MY_SECRET',
response: recaptcha
};
post_req = https.request('https://www.google.com/recaptcha/api/siteverify', function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('CHUNK: ', chunk);
});
});
post_req.on('error', function (e) {
console.log('ERROR: ', e);
callback(false);
});
post_req.write(requestBody);
post_req.end();
The result is:
{
"success": false,
"error-codes": [
"missing-input-response",
"missing-input-secret"
]
}
Finally found a solution. It seems the issue was with the Content-Type.
This works:
var request = require('request');
...
request.post(
'https://www.google.com/recaptcha/api/siteverify',
{
form: {
secret: 'MY_SECRET',
response: recaptcha
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
When i run code given below in terminal than i get following error:-
ReferenceError: resolve is not defined.
const request = require('request');
let geoLocationPromise = (zipCode) => {
return new Promise(()=>{
request({
url:`https://maps.google.com/maps/api/geocode/json?address=${zipCode}`,
JSON: true
}, (error, response, body)=>{
if(error){
reject('Unable to connect to server');
}else if (response.statusCode === 200) {
console.log(body);
resolve(JSON.parse(body.currently, undefined, 2));
}
});
});
};
geoLocationPromise(841101).then((loc)=>{
console.log(loc);
}, (errorMessage)=>{
console.log(errorMessage);
});
You need to declare the parameters “reject” and “resolve” for your Promise's callback, like this:
const request = require('request');
let geoLocationPromise = (zipCode) => {
return new Promise((resolve, reject)=>{
request({
url:`https://maps.google.com/maps/api/geocode/json?address=${zipCode}`,
JSON: true
}, (error, response, body)=>{
if(error){
reject('Unable to connect to server');
}else if (response.statusCode === 200) {
console.log(body);
resolve(JSON.parse(body.currently, undefined, 2));
}
});
});
};
module.exports.login = function (request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
I am using connect with body-parser. When I first time open this app I see login form - nice, but when I submit a form I see in a console 405 Method not allowed error. I was trying to add some headers but it didn't work. Anyone can help?
I finally solved it. The problem was serve-static and serve-index. It was written some extra headers like allowed methods!
I believe the syntax should be:
module.exports = function(request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
or
function login(request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
module.exports = login;
I'm trying a pretty complex computation in my code below. I'm trying to get the list of bugs from github in the given project using the api https://api.github.com/repos/marklogic/java-client-api/issues?page=1&per_page=10. From the list of bugs I'm trying to get each issues' corresponding events and comments from their corresponding endpoints ex: https://api.github.com/repos/marklogic/java-client-api/issues/291/events and https://api.github.com/repos/marklogic/java-client-api/issues/291/comments.
I'm using async library. I'm using waterfall function and parallel function to return a consolidated JSON for each bug such that each issue will have comment, & events in the same response for each issue. The problem is its throwing Can't set headers after they are sent error & its pointing to line 2 lines, I understand what the error is saying but I can't figure out how to fix it, because commenting out either of the offending lines results in request hang because the server is not sending the response. Please help! Thanks in advance
exports.listGitHubBugs = function(req, res) {
var _page = req.query.page || 1;
var _per_page = req.query.per_page || 25;
var finalResult = []
//console.log('url:', 'https://api.github.com/repos/marklogic/' + req.query.project + '/issues?page=' + _page + '&per_page=' + _per_page);
var options = {
url: 'https://api.github.com/repos/marklogic/' + req.query.project + '/issues?page=' + _page + '&per_page=' + _per_page,
headers: {
'User-Agent': req.query.project
},
auth: githubAuth
};
request(options, function(error, response, body) {
if (error) {
console.log(error);
res.send(error);
}
if (!error && response.statusCode === 200) {
var issues = JSON.parse(response.body)
async.waterfall([
// get comments & events for all bugs and then send the response
function(callback) {
issues.forEach(function(issue) {
// for each bug, get comments and events
async.parallel([
function(parallelCallback) {
var options = {
url: issue.events_url,
headers: {
'User-Agent': getProjectNameFromURL(issue.events_url)
},
auth: githubAuth
};
request(options, function(error, response, body) {
if (error) {
console.log('ERROR', error);
parallelCallback(error)
}
if (!error && response.statusCode === 200) {
// console.log('events:', body);
parallelCallback(null, body)
}
})
},
function(parallelCallback) {
var options = {
url: issue.comments_url,
headers: {
'User-Agent': getProjectNameFromURL(issue.comments_url)
},
auth: githubAuth
};
request(options, function(error, response, body) {
if (error) {
console.log('ERROR', error);
parallelCallback(error)
}
if (!error && response.statusCode === 200) {
// console.log('comments:', body);
parallelCallback(null, body)
}
})
}
], function(err, result) {
if (err) {
console.log('ERROR:', err);
callback(err);
}
console.log('parallel process done');
issue.events = JSON.parse(result[0]);
issue.comments = JSON.parse(result[1]);
finalResult.push(issue)
callback(null, finalResult) // offending line#1
})
}) // forEach end
}
], function(err, result) {
if (err) {
res.send(err);
}
console.log('waterfall done');
console.log(result);
res.send(result); // offending line#2
})
} // if end
}) // reqest end
}
Error
UncaughtException: Can't set headers after they are sent.
ERROR Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
at ServerResponse.res.set.res.header (/Users/sreddy/space/angularjs/BugTrack/node_modules/express/lib/response.js:524:10)
at ServerResponse.res.send (/Users/sreddy/space/angularjs/BugTrack/node_modules/express/lib/response.js:125:10)
at ServerResponse.res.json (/Users/sreddy/space/angularjs/BugTrack/node_modules/express/lib/response.js:191:15)
at /Users/sreddy/space/angularjs/BugTrack/server/api/common/common.controller.js:163:33
at /Users/sreddy/space/angularjs/BugTrack/server/api/common/common.controller.js:153:29
at /Users/sreddy/space/angularjs/BugTrack/node_modules/async/lib/async.js:254:17
at done (/Users/sreddy/space/angularjs/BugTrack/node_modules/async/lib/async.js:135:19)
at /Users/sreddy/space/angularjs/BugTrack/node_modules/async/lib/async.js:32:16
at /Users/sreddy/space/angularjs/BugTrack/node_modules/async/lib/async.js:251:21
Final working code
exports.listGitHubBugs = function(req, res) {
var _page = req.query.page || 1;
var _per_page = req.query.per_page || 25;
var finalResult = []
//console.log('url:', 'https://api.github.com/repos/marklogic/' + req.query.project + '/issues?page=' + _page + '&per_page=' + _per_page);
var options = {
url: 'https://api.github.com/repos/marklogic/' + req.query.project + '/issues?page=' + _page + '&per_page=' + _per_page,
headers: {
'User-Agent': req.query.project
},
auth: githubAuth
};
request(options, function(error, response, body) {
if (error) {
console.log(error);
return res.send(error);
}
if (!error && response.statusCode === 200) {
var issues = JSON.parse(response.body)
async.waterfall([
// get events and comments for all bugs and return the final processes list of bugs
function getEventsAndCommentsForAllBugs(callback) {
issues.forEach(function getEventsAndComments(issue, index) {
// for each bug, get comments and events
async.parallel([
function getEvents(parallelCallback) {
var options = {
url: issue.events_url,
headers: {
'User-Agent': getProjectNameFromURL(issue.events_url)
},
auth: githubAuth
};
request(options, function(error, response, body) {
if (error) {
console.log('ERROR', error);
parallelCallback(error)
}
if (response.statusCode === 200) {
// console.log('events:', body);
parallelCallback(null, body)
}
})
},
function getComments(parallelCallback) {
var options = {
url: issue.comments_url,
headers: {
'User-Agent': getProjectNameFromURL(issue.comments_url)
},
auth: githubAuth
};
request(options, function(error, response, body) {
if (error) {
console.log('ERROR', error);
parallelCallback(error)
}
if (response.statusCode === 200) {
// console.log('comments:', body);
parallelCallback(null, body)
}
})
}
], function attachEventsAndComments(err, result) {
if (err) {
console.log('ERROR:', err);
callback(err);
}
console.log('parallel process done');
issue.eventList = JSON.parse(result[0]);
issue.commentList= JSON.parse(result[1]);
finalResult.push(issue)
if (index === (issues.length - 1)) {
callback(null, finalResult)
}
//
})
}) // forEach end
}
], function processedBugs(err, result) {
if (err) {
res.send(err);
}
console.log('waterfall done');
console.log(result);
res.send(result);
})
} // if end
}) // reqest end
}
could you provide a complete working example of the code, something we can try.
this said, there are several errors in this source code.
Onthe first request, if an error occurs, you write it in app.response,, but you don t stop execution. Thus, if an error occurs, you ll write twice the response object.
You should do
if (error) {
console.log(error);
return res.send(error);
}
instead of
if (error) {
console.log(error);
res.send(error);
}
Then, this can be changed
if (!error && response.statusCode === 200) {
to
if (response.statusCode === 200) {
Same mistake occurs while fetching issues events and comments, please consider to fix it.
And also in the final callback of async.//
And in the final callback of async.waterfall.
finally, i suggest you to make use of named functions. That would help you to debug by providing more meaningfull error stack trace.
For example instead of doing,
async.prallel([function(){/* code here*/}]);
You would write
async.parallel([function nameOfTheTask(){/* code here*/}]);
consider also to use a linter such as eslint, several missing ; could break your code, see http://eslint.org/
I figured it out. I was calling the parellelCallback() for every iteration instead of calling it at the end of the loop. Simple if condition was all that was required.
if (index === (issues.length-1)) {
callback(null, finalResult)
}
I tried to insert new image to google-picasa album using Gdata api authenticate via oauth2.0 from request.js node.js module.
My Function:
insertPhoto(options,callback){
fs.readFile('C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg',"base64",function(error,data){
var userId=options.userId || 'default';
var rootUrl='https://picasaweb.google.com/data/feed/api/user/'+userId+'/albumid/'+options.albumId+'';
var body_data=gen_multipart('testing.jpg','sss',data,'image/jpeg');
request({
method:'POST',
headers:{ 'GData-Version': '2','Authorization':'Bearer' + ' ' + 'my_access_token',"Content-Type":'multipart/related; boundary="END_OF_PART"','Content-Length':body_data.length,"MIME-version":"1.0"},
body:body_data,
uri:rootUrl
},callback);
});
}
Passing options and callback to my function
insertPhoto({albumId:'5917473565459053457'},function(error,success){
if(error){
console.log(error);
}else{
console.log(success);
}
});
The following is my output
{ status: 400, message: 'Not an image.' }
Not an image.
what error is this my header and request body which i made is same as in google documentation.
refer: https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#PostPhotos
what i did wrong can any one help me!!
I think the problem is that you use "base64" should be binary
This code seem to do the work for me:
var fs = require('fs');
var request = require('request');
exports.upload = function(fileName, options, callback) {
fs.readFile(fileName,function(error,data) {
if (error) {
callback(error, null, null);
}
else {
console.log('Read file', data.length);
var token = options.token;
var userId = options.userId || 'default';
var rootUrl = 'https://picasaweb.google.com/data/feed/api/user/'+
userId+'/albumid/'+
options.albumId+'';
request({
method:'POST',
headers:{
'GData-Version': '2',
'Authorization':'Bearer' + ' ' + token,
"Content-Type":'image/jpeg',
'Content-Length':data.length,
"MIME-version":"1.0"},
body:data,
uri:rootUrl
},callback);
}
});
};
And the calling test program:
var imageUpload = require('./imageUpload');
var parseString = require('xml2js').parseString;
imageUpload.upload('...fileName...', {
albumId: '....',
userId: '...',
token: '...'
},
function(error, response, body) {
if (body && (response.statusCode === 200 || response.statusCode === 201 || response.statusCode === 202)) {
parseString(body, function (err, result) {
console.dir(result);
if (!err) {
console.dir(result.entry['media:group'][0]['media:content'][0].$.url);
}
else {
console.error('Error', err);
}
});
}
else {
console.error('Error', response.statusCode, body);
}
});