Why is my Parse Cloud Code request 'unauthorized?' - javascript

I'm trying to run Parse cloud code for the first time from an AngularJS app. I keep getting the Parse.Error 'unauthorized' in my console.log. I've initialized Parse in my application and JS keys. Where am I going wrong?
Angular Code Format:
$scope.runSomething = function () {
Parse.Cloud.run('nameFunction', req.body, {
success: function (result){
},
error: function (error){
console.log(error);
}
})
I derive the req.body for the Parse.Cloud.run from prestanding info in the $scope.runSomething function.
My truncated main.js:
Parse.Cloud.define('nameFunction', function(request, response){
Parse.Cloud.useMasterKey();
//Do Stuff})
I'm sure I'm missing something small but I have no idea what.

It sounds like you're close. Cloud functions (including before/after functions) must call success or error on the response object to properly complete, so...
Parse.Cloud.define('nameFunction', function(request, response){
Parse.Cloud.useMasterKey();
var someParam = request.params.someParam;
doSomePromiseReturningThing(someParam).then(function(result) {
response.success(result);
}, function (error) {
response.error(error);
});
});

Related

Socket.io-emit in callback gives SyntaxError: Unexpected end of JSON input

So I'm exporting a callback-function in a module like this:
(function() {
let request = require("request");
module.exports = function GithubApi(url, callback) {
let options = {
uri: url,
headers: {
"User-Agent": "Me",
"Content-Type": "application/x-www-form-urlencoded"
}
};
request(options, function(err, body) {
let context = {
issues: JSON.parse(body.body).map(function(issue) {
return {
title: issue.title,
comments: issue.comments,
};
})
};
callback(context) // The callback
});
};
}());
And this callback works perfectly fine when I'm using it in my GET-request with express.js:
app.get("/", (req, res) => {
let url = "some url";
GithubApi(url, (data) => {
res.render("../some-views", data);
});
});
But when I add a socket-emit, the callback-function returns SyntaxError: Unexpected end of JSON input
app.get("/", (req, res) => {
let url = "some url";
GithubApi(url, (data) => {
io.socket.emit("update", {message: data}); // adding this
res.render("../some-views", data);
});
});
Can't understand why the socket would interfere with the request and return an error with JSON. Can anybody help?
The probablem must be caused by the fact that body.body doesn't contain a valid JSON string.
When you run code like this:
JSON.parse(body.body)
you should always use try/catch because JSON.parse throws exceptions on bad JSON.
See those answers for more details:
Calling a JSON API with Node.js
Node JS ignores undefined check
How to extract inner string from the array string
Node server crashes in parsing JSON
So the problem was with the io.sockets.emit("update", {message: data});. For some reason, that interfered with the request(still don't know why tough). I guess it has something to do with the socket broadcasting to all channels, and that causes some kind of error, read something about it here.
So I changed the call to the callback-function to this:
GithubApi(orgs, repo, token, (data) => {
io.of("/").emit("update", {message: data}); // This line made it work
res.render("../views/home", data);
});

Grab events from Eventbrite API with Nodejs

So I'm unable to find any examples and the example used on the npm package README throws me an error.
So I'm using https://github.com/Datahero/node-eventbrite
I require it in app.js. I create the token variable and place my token in there.
I add this piece of snippet in
try {
var api = eventbriteAPI({
token: eventbrite_token,
version : 'v3'
});
} catch (error) {
console.log(error.message); // the options are missing, this function throws an error.
}
So on the README file it says the next line of code should be something like (replacing the user_id: with my user id).
api.owned_events({ user_id: 30 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});
I get the error TypeError: api.owned_events is not a function
Basically I'm trying to get a list of events based on the location from the Eventbrite API via node. But I'm unable to even query from node and get what I want back. Has anyone any resources or can offer help?
Thank you!
I think there is an error on the README file, api should be declared outside the try/catch block:
var api;
try {
api = eventbriteAPI({
token: eventbrite_token,
version : 'v3'
});
} catch (error) {
console.log(error.message);
}
api.owned_events({ user_id: 30 }, function (error, data) {
if (error)
console.log(error.message);
else
console.log(JSON.stringify(data)); // Do something with your data!
});

Error with Twitter Nodejs query

I've tried a few variations of this snippet. I keep getting the same undefined error when trying to print a json object to the console. Thanks in advance.
var userTweets = client.get('statuses/user_timeline', function(error, tweets, response){
if(error) throw error;
return tweets
});
console.log(userTweets)
client.get is asynchronous
This code is working, then you have to manage your code to wait for asynchronous response.
client.get('statuses/user_timeline', function(error, tweets, response){
if(error) throw error;
console.log(tweets)
});
If you have some code after client.get, you should do that
before :
var userTweets = client.get(..., function() {});
// do some code
console.log(userTweets);
after :
client.get(....., function(error, tweets) {
...
otherCode(tweets);
});
function otherCode(userTweets) {
// do some code
console.log(userTweets);
}
I suggest you to read this answer : https://stackoverflow.com/a/11233849/5384802 to understand asynchronous code.

Passing multiple error messages through callback?

I am using the got library to make some http requests. A typical got request looks like this:
got.post(url, options, function(err, body, res) {
...
}
The callback has errors as well as the body content and the full response. In some cases when connecting to certain 3rd party APIs, if I get an error response, I find both the err and body both contain important error information I would want to pass back up the chain of callbacks:
API.prototype.makeRequest = function(callback) {
got.post(url, {}, function(err, body, res) {
if (err) {
callback(err);
return false;
}
// Otherwise do stuff
});
}
// app.js
var myAPI = new API();
myAPI.makeRequest(function(err, data){
if (err) {
console.log(err);
return false;
}
// Do stuff...
});
So in this example, I'm obviously only returning the error for the response. An example of this error:
{ [HTTPError: Response code 400 (Bad Request)]
message: 'Response code 400 (Bad Request)',
code: undefined,
host: 'api.someservice.com',
hostname: 'api.someservice.com',
method: 'POST',
path: '/oauth2/token_access',
statusCode: 400,
statusMessage: 'Bad Request' }
But if I examine the body of the error request, I see even more important and relevant error information:
{ error_description: 'Grant type is not supported: some_type_of_grant', error: 'unsupported_grant_type' }
So I have useful information in both the err and body variables that I want to pass back up the callback chain since both are useful.
What is the best approach to this? Typical Node.js approach seems to be having a single err value be the first value in the callback. Should I combine them into a single object or combine them and formulate my own error? Any other good approaches?

How can I structure these callbacks to get me the info I want?

Maybe I've been staring at my code too long or maybe I'm using too many callbacks elsewhere or something, but I can't figure out the logistics of this one. I know the value contained in rows is correct from using util.inspect(rows) on it inside that callback function. I just don't know how to bring it back up to the surface, so to speak. dbHandler() is called from other functions that pass the params and a result is expected in return.
Any insight would be tremendously helpful.
Using node.js with Express and mysql packages if that makes a difference.
function dbHandler(req, res, params) {
pool_user.getConnection(function (err, connection) {
if (err) {
connection.release();
res.json({
"code" : 100,
"status" : "Error in connection database"
});
return;
}
connection.query(params.query_string, function (err, rows) {
connection.release();
if(!err) {
res.json(rows); // <<--- I want to get ahold of the value of `rows`
//console.log(util.inspect(rows));
}
});
connection.on('error', function(err) {
res.json({
"code" : 100,
"status" : "Error in connection database"
});
return;
});
});
}
Trying to return the result of an async function is an anti-pattern and will never work.
Instead, restructure the calling code.
Not Like This - the anonymous callback does not return to the caller
new_data = api_request_data(auth, request,
function(error, data){
return data;
});
store(new_data);
update_screen(new_data);
Better
api_request_data(auth, request,
function(error, data){
store(data);
update_screen(data);
});
Best
api_request_data(auth, request,
function(error, data){
if (error){
console.log(error);
return;
}
store(data);
update_screen(data);
});
In your code, the data pipeline looks ok.
connection.query(params.query_string, function (err, rows) {
connection.release();
if(!err) {
res.json(rows); // <<--- I want to get ahold of the value of `rows`
//console.log(util.inspect(rows));
}
});
The code res.json(rows); in a node.js application will queue a JSON string containing the data in rows for writing to the current web connection referenced in res.
Your question suggests that the issue is that this line does not return data to the caller of dbHandler(), but no trained node.js developer would expect that to happen. The code looks correct for delivering the data in rows to an over-the-web client of the node.js application.

Categories