Parse save always error - javascript

Parse.initialize(ApiKeys.appId, ApiKeys.jsKey, ApiKeys.masterKey);
function submit(){
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
debug_log("score success");
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
debug_log("score error");
}
});
}
I am sure that I have already config the keys. But I still cannot save, everytime, when I submit, it give me back error.
I use back{4}app instead of parse, is there something important was ignored by me?
Thanks in advance.

You should provide the error code and its message.
The code seems ok, check your keys and settings.
Check the error message
not authorized=> keys not matched.
something like you are without permission to XXX=> check the class level permission (CLP)
or you have the beforeSave on cloud code, check response.success() have been called.

Add
Parse.serverURL="back4app api URL"
Solve the ptoblem.

Related

Error from nodejs server thrown not being passed back to AJAX

I have the following AJAX that will send the entered data to the node server and the controller will check whether such data exist in the database or not.
If I do enter the data correctly, then everything is working fine.
However, I tried enter anything that the database does not have and it immediately throw an error, causing the server to stop. The error said that I did not handle the event, so I tried with res.json(err) in the controller instead of throw new Error, hoping that the error will be passed back to AJAX under the error key, but it is still not working. The error still gets thrown and the node server terminate itself.
I would like the server to continue and alert to the user that the data that was entered is not in the database but I have no idea why my approach is not correct.
I was thinking of using this SO thread if I'm able to get the error message back first from server side.
jQuery Ajax error handling, show custom exception messages
To solve the server from stopping, I used the code in app.js that was referred from this link
How do I prevent node.js from crashing? try-catch doesn't work
I'm not sure whether should I use the accepted answer for my case.
function createProduct(inputval){
let inputAction = window.location.pathname;
$.ajax({
type: "POST",
url: inputAction,
data: {order: inputval.split('-')[0].trim(), lot: inputval.split('-')[1].substring(0,5)},
success: function(data) {
$('#product').val('');
//Another function to add HTML
display(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("XHR" + jqXHR)
console.log("Status" + textStatus)
console.log(errorThrown)
}
});
}
Controller File
exports.createProduct = function (req, res) {
db.Product.findOne({ "order": req.body.order, "lot": req.body.lot }).exec(function (err, product) {
if (!product || err){
throw new Error("The product entered returns null");
}
res.json(product);
});
};
Main File: app.js
process.on('uncaughtException', function (err) {
console.error(err);
console.log("Node NOT Exiting...");
});
You should use correct status code for your response. I suggest change your controller like below snippet
exports.createProduct = function (req, res) {
db.Product.findOne({ "order": req.body.order, "lot": req.body.lot }).exec(function (err, product) {
if (err){
res.status(500).end();//means internal server error
} else if (!product) {
res.status(404).end();//means product not found
} else {
res.json(product);
}
});
};
I finally figure it out thanks to feedback from other community, so I thought I would just share it here. It's so simple and silly me for neglecting such statement.
First, the code in app.js can just be removed.
Second, based on the answer given by #Milad Aghamohammadi. Instead of just:
res.status(500).end();
Use:
return res.status(500).json({err: "Server error"});
This way, the error is able to be handled by the AJAX error function and the node server will not be terminated from the event loop.

Javascript: Change Global Var Locally

Easy question. Just an explict look:
var token = "12345"
function einloggen(){
var test = particle.login({username: userName, password: passWord});
test.then(
function (data) {
token = data.body.access_token;
console.log('tokenoutprint1:', token);
},
function (err) {
console.log('LoggingIn Failed', err);
}
);
console.log('tokenoutprint2:', token);
}
einloggen();
after that i want to reuse the "new" token in a different Function...
callFunctionAVC(token);
The third last line will print me 12345. But I want print out the "new" token, defined in. Like in "normal" java
I don't know why because the first console.log shows me the right token.
SO HOW DO I GET THE "TOKEN" TO A GLOBAL VARIABLE. Thats my "real" Question. Please send full codes only otherwise i won't get it.
Sorry for not being a pro, I'm just learning in school.
Greetings.
The einloggen function is not (visibly) being called before the console.log, which means you set token = "12345", console.log() it and some time later you may or may not call the einloggen function.
I think what you wanted to do is:
function einloggen() {
//your code
}
einloggen(); // Execute the method
console.log(token);
There's a possibility this won't work as expected as well because you're using Promises in your einloggen function.
You could also try to execute console.log(token) from the developer console of your browser.

Parse Cloud query error

I am trying to build a simple background job on the Parse Cloud. Right now, I'm just testing, but I am having a problem when performing a query.
If I comment out:
//query.ascending("createdAt");
the console log shows all the messages and no errors. If I don't comment it out, I get an error. Can anybody explain why this is happening? Is it an authentication error?
Parse.Cloud.job("cleanPosts", function(request, status) {
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.ascending("createdAt");
query.each(function(post) {
console.log( "objectId:" + post.get("message") );
}).then(function() {
status.success("Success");
}, function(error) {
status.error();
});
});
When using Parse.Query.each, you do not need to (and cannot) provide an orderBy. It will run the callback for every object (actually ordered by objectId).
The official error is "Cannot iterate on a query with sort, skip, or limit." and it should appear if you log that in the error block.

Parse save method gives 400 error

The following code doesn't save anything to the database:
var UserObject = Parse.Object.extend("User");
var objectid = object.id;
var secondQuery = new Parse.Query(UserObject);
secondQuery.get(objectid, {
success: function(userObject) {
alert(userObject.get("fbId"));
userObject.set("provider_access_token", access_token);
userObject.set("provider_refresh_token", refresh_token);
userObject.set("provider_token_expire", expires_in);
userObject.save(null, {
error: function(error){
alert(error.message + error.code);
}
});
},
error: function(object, error) {
alert("Error:" + error.code + " " + error.message);
}
});
I'm not sure why, but it does give me an 400 HTTP error. What am I doing wrong?
I've checked that all my variables are set and correct (the alert works just fine).
You have a typo: errror > error
Fixing this will give you the real error of why isn't getting saved
Thanks to Juan Guarcia who pointed out that I had an type which led to the error not showing up. After fixing that my problem was easily solved.
The error I was getting was the following:
Parse::UserCannotBeAlteredWithoutSessionError206
Which means that user objects cannot be altered without using the master key of my application. However, this isn't supported inside the Parse Javascript SDK, only in the Cloud Code.
So I need to move the function to the Cloud Code and then save from there. Problem solved!

Check whether url returns 404

I'm trying to check whether an URL returns 404, 403 etc when including a Javascript file. It works ok, but I still get an error in "Chrome developer tools".
This is my code:
(function() {
try
{
var ml = document.createElement('script');
ml.type = 'text/javascript';
ml.async = true;
ml.id = 'monoloop_invoke';
ml.onerror = function(){alert('File does not exist');};
ml.src = 'http://somedomain.com/somefile.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ml, s);
}
catch(err)
{
alert('Error: '+err);
}
})
();
If the file does not exist it shows the error "File does not exist" from the ml.onerror function. This is all good. But the problem is that I still get an error line in my console like:
GET http://somedomain.com/somefile.js 403 (Forbidden)
and the try/catch does not catch this error.
Anyone knows how to solve this? Or is there another way of testing if a URL exists before including it? I cannot use AJAX as I need to use this in a cross-domain fashion. I could use jQuery if necessary.
EDIT: It does not show an error in IE, so i guess this maybe just relates to the way chrome reports issues. Does anyone see a more elegant solution for checking if a file exisists without genreting anything in the console.
jQuery.getScript( url, [ success(data, textStatus) ] )
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
url
A string containing the URL to which the request is sent.
success(data, textStatus)
A callback function that is executed if the request succeeds.
To catch the errors use the ajaxError event:
http://api.jquery.com/ajaxError/

Categories