I use Parse.com cloud to manage my database for mobile application. When I save in table user some user with the same username or email it gives me the error:
POST https://api.parse.com/1/users 400 (Bad Request)
I understood by myself that error appears when the username or email are the same in different users. Is there a method to return the reason of the error like "this mail is already chosen"? Below my code:
saveUser: function() {
this.utente.save(null, {
success: function(persona) {
//console.log("modello salvato nel db");
var id = persona.get("objectId");
window.localStorage.setItem('parseId', id);
},
error: function(error) {
alert("Save error");
console.log(error);
}
});
},
Looks like you aren't using response.error(error) anywhere...
Try
saveUser: function() {
this.utente.save(null, {
success: function(persona) {
//console.log("modello salvato nel db");
var id = persona.get("objectId");
window.localStorage.setItem('parseId', id);
},
error: function(error) {
response.error(error);
}
});
}
And then in your native script console.log the error.code and error.message.
Related
So I have some cloud code I am trying to write to like a post.
My database is setup that users have a likedPosts array, which has object id's of all the posts that the user liked. Users also have a column coins, that should get incremented when users like their posts.
The post object has a likes column which is an integer that gets incremented with each like, and the post object also has a posterId column, which is the object id of the user that posted it.
Here is my function right now (I am not very good at javascript and cloud code, so if there is something horribly wrong, I'm sorry)
Parse.Cloud.define("likePost", function(request, response) {
Parse.Cloud.useMasterKey();
var senderId = request.params.senderId;
var postId = request.params.postId;
var post = new Parse.Object ({objectId: postId});
var posterId = post.posterId
var poster = new Parse.User ({objectId: posterId});
var sender = new Parse.User ({objectId: senderId});
sender.add("likedPosts", postId);
poster.increment("coins");
post.increment("likes");
poster.save(null, {useMasterKey:true, success:
function(poster) {
console.log("Successfully saved poster");
}, error: function(poster, error) {
console.error("Error saving poster: " + error.message);
response.error(error);
}
});
post.save(null,{useMasterKey:true, success:
function(post) {
console.log("Successfully saved post");
}, error: function(post, error) {
console.error("Error saving post: " + error.message);
response.error(error);
}
});
sender.save(null, {useMasterKey:true, success:
function(sender) {
console.log("Successfully saved sender");
}, error: function(sender, error) {
console.error("Error saving sender: " + error.message);
response.error(error);
}
});
response.success();
});
I call the function from swift like so:
PFCloud.callFunction(inBackground: "likePost", withParameters: ["senderId" : PFUser.current()!.objectId!, " postId": postObject!.objectId!], block: { (result, error) in
if (error != nil) {
print(error!)
} else {
print("success liking")
}
})
In my logs, however, I get the following error:
2017-06-21T21:47:59.499Z - Failed running cloud function likePost for user R4d8Zrcdhw with:
Input: {"senderId":"R4d8Zrcdhw"," postId":"XXbu55PdpR"}
Error: {"code":141,"message":{"code":200,"message":"bad or missing username"}}
2017-06-21T21:47:59.492Z - bad or missing username
My guess is that the request is missing a header to define the content-type. I've seen Parse return the "bad or missing username" error via the Parse REST API if the Swift URLSession was using an incorrect content-type header.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or
Parse.Cloud.httpRequest({
url: 'http://www.example.com/',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
in my code I have a Factory with ng.resource:
.factory('company', function($resource){
return $resource(appHelper.apiPath('auth/company/info'), {}, {
update: {
method: "PUT"
}
});
});
If I submit the form in my Controller everything works fine as far as the api gives a positive response.
In case of an error the api returns a json object with http 200. In my callback function I validate the response:
$scope.saveCompanyForm = function (company) {
company.$update(
function(data) {
if(data.status == 'ERROR') {
alert("error from api")
} else {
alert("no error")
}
}, function(error) {
alert("error")
}
The problem is if the api returns an error the form cleared.
If the API response with http 500 or http 404 the form is not cleared.
Is there any possibility to prevent angular to reset the form?
Thanks
best
You can always save it before and apply after the callback.
$scope.saveCompanyForm = function (company) {
var saved_company = company;
company.$update(
function(data) {
if(data.status == 'ERROR') {
alert("error from api")
company = saved_company;
} else {
alert("no error")
company = saved_company;
}
}, function(error) {
alert("error")
company = saved_company;
}
Here I'm sending a mail when the form is submitted. Everything is working fine, the only issue is even though the mail is not sent because of wrong authentication or internet problem ,the user is getting the success message. I want that the user should get an error message if the mail is failed to get sent.
client
this.mail= function() {
var data = ({
name :this.name,
email :this.email
})
//Post Request
$http({
method: 'POST',
url: '/contact2', data
}).then(function successCallback(response) {
$mdToast.show(
$mdToast.simple()
.textContent('Thanks for your message '+data.name)
.position($scope.getToastPosition())
.hideDelay(5000)
);
}, function errorCallback(response) {
$mdToast.show(
$mdToast.simple()
.textContent('Something went wrong, Please TRY AGAIN '+data.name)
.position($scope.getToastPosition())
.hideDelay(5000)
);
});
});
server
function send(req, res) {
console.log(req.body);
var data= req.body
smtpTransport.sendMail({
from: "<email#gmail.com>",
to: data.email,
subject: "Website Submission from "+data.name,
text: 'You have a new submission with the following details...,
}, function(error, response){ //callback
if(error){
console.log(error);
}if{
console.log(" Message sent "+data.name);
}
smtpTransport.close();
});
res.json(data);
}
Server : You can create and send error message from server as
if(error){
res.json({
Status : false,
message : error
})
}else{
res.json({ Status : true,
message : 'Success'
})
}
Client : Here you can capture it by
function successCallback(response) {
if(response.Status){
console.log(response.message);
}// for success
else{
console.log(response.message)
} //for error
}
You can set and send additional data.emailSent = true or data.emailSent = false as:
if(error){
data.emailSent = false;
} else{
data.emailSent = true;
}
On client you can check this flag and show success or failure accordingly.
Thank Zeeshan Hassan and pooja for helping me out, at first I was unable to access the status and message . I just made these few changes to Pooja's solution and its working
function successCallback(response) {
console.log(response.data.Status);
if (response.data.Status){console.log(response.data.message);}
` `else{ console.log(response.data.message) }
I am facing 2 issues with writing a background job in parse
Here is my code
Parse.Cloud.job("createSilentUsers",function(request,response){
// Set up to modify user data
Parse.Cloud.useMasterKey();
//get all the users from backupusers table where isbiscootactivated = 0 and issnsactivated=0
// Query for all users
var query = new Parse.Query("biscootusers");
query.equalTo("isbiscootactivated",0);
query.equalTo("issnsactivated",0);
query.first({
success: function(result) {
// Successfully retrieved the object.
var objUser = result;
console.log(result.attributes.deviceid);
console.log(result.attributes.imei);
console.log(result.attributes.appname);
console.log(result.attributes.appid);
console.log(result.attributes.appversion);
//check if the deviceid and imei set is already a biscoot activated user
var promise = Parse.Promise.as();
promise = promise.then(function() {
console.log("we are inside the prmise");
return Parse.Cloud.httpRequest({
method: 'POST',
url: 'http://<our server name>/1.0/PartnerActivation/isDeviceExists',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'},
body: {
imei: result.attributes.imei,
deviceid: result.attributes.deviceid,
appname: result.attributes.appname,
appid: result.attributes.appid,
appversion: result.attributes.appversion}
}).then(function(httpResponse)
{
console.log("Response of isdeviceactivated is " + httpResponse.text);
if(httpResponse.text == 'true' || httpResponse.text="True")
{
console.log("The user is already activated");
objUser.set("isbiscootactivated",1);
objUser.save();
}
else
{
//do the biscoot activation here
console.log("its not activated, lets do the biscootusers activation");
}
},
function(error) {
console.log("error occurred during isDeviceExists api as " + error);
});
});
console.log("nothing seems to have happened");
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
}).then(function() {
// Set the job's success status
status.success("All the users been set to the db successfully");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong.");
});
});
The Issues I have are
In the logs I frequently see this error
Ran job createSilentUsers with:
Input: {}
Failed with: ReferenceError: status is not defined
at main.js:74:9
at r (Parse.js:2:4981)
at Parse.js:2:4531
at Array.forEach (native)
at Object.E.each.E.forEach [as _arrayEach] (Parse.js:1:666)
at n.extend.resolve (Parse.js:2:4482)
at null. (Parse.js:2:5061)
at r (Parse.js:2:4981)
at n.extend.then (Parse.js:2:5327)
at r (Parse.js:2:5035)
The http request just doesn't seem to work, while it always does if I test it from some http REST client.
Just change the "response" to "status" on the funcion header.
Parse.Cloud.job("createSilentUsers",function(request,response){
to this
Parse.Cloud.job("createSilentUsers",function(request,status){
In express js, I have the following code which sends a response over to Backbone:
if (!user) {
req.session.messages = [info.message];
return res.send(400, howCanIsendTheErrorMessageAlso);
}
How can I send the error message also, together with the error code?
How can Backbone receive it?
Any ideas?
In backbone, I have the following code:
loginModel.save({
username : obj.elEmail.val(),
password : obj.elPassword.val(),
admin : false
}, {
success: function (e) {
console.log('success');
},
error: function (e) {
console.log(e);
}
});
Any ideas?
You send it from express with:
res.send(500, { error: "hi, there was an error" });
In Backbone the parameters of your error callback are: model, xhr, options
So you need to extract your error message fron the xhr object in the error callback like this:
obj.save(
{
data:"something"
},
{
success: function(model, response, options){
console.log("worked");
},
error: function(model, xhr, options){
console.log("error", xhr.responseText);
}
}
);
in your express app (for example):
res.send(403, {
error: "some elaborate error message"
});
Your Backbone code is correct, you'll see the error
regarding error codes, I would recommend sticking to this list http://en.wikipedia.org/wiki/List_of_HTTP_status_codes