I am building a web application using Parse.com as my backend. I have run into a problem when trying to store the response from Facebook's user profile API in a Parse database.
FB.api('/me', function(response) {
// Print Response to Console
console.log(response);
// Create New Parse Object
var Facebook = Parse.Object.extend("Facebook");
var userFacebook = new Facebook();
for(var element in response) {
userFacebook.set(element, response[element]);
}
// Store Data on Parse
userFacebook.save(null, {
success: function(user) {
console.log("User Facebook data saved.");
},
error: function(user, error) {
console.log("Facebook data storage error: " + error.code + " (" + error.message + ")");
}
});
The API response prints correctly to the console, and I receive two error messages, one after the other:
Failed to load resource: the server responded with a status of 404
(Not Found) https://api.parse.com/1/classes/Facebook/myID
and
Facebook data storage error: 101 (object not found for update)
In my Parse account, a database titled "Facebook" is created. However, it only contains a header for each of the elements in the response object (e.g., first_name, gender, email, etc.). It does not have a new row with these values.
I am really stuck on this one -- any help would be appreciated!
Note that the response object is in the form:
{
"email":"email#example.com",
"first_name":"myFirstName",
"gender":"myGender",
"id":"myID",
"last_name":"myLastName",
"link":"https://www.facebook.com/app_scoped_user_id/myID/",
"locale":"en_US",
"name":"myFullName",
"timezone":-7,
"updated_time":"2014-03-12T04:57:39+0000",
"verified":true
}
The object in for each loop
for(var element in response) {
userFacebook.set(element, response[element]);
}
FB.api('/me', function(response) {
// Print Response to Console
console.log(response);
// Create New Parse Object
var Facebook = Parse.Object.extend("Facebook");
var userFacebook = new Facebook();
for(var element in response) {
userFacebook.set(element, response[element]);
}
// Store Data on Parse
userFacebook.save(null, {
success: function(user) {
console.log("User Facebook data saved.");
},
error: function(user, error) {
console.log("Facebook data storage error: " + error.code + " (" + error.message + ")");
}
});
The "id" column on a Parse.Object is protected and cannot be set via the API. In my case, Facebook's API response includes an "id" key, which is colliding with the Parse.Object "id" key.
If you are running into the same problem, you simply need to change the name of the "id" column. You can do this with the following code:
for(var element in response) {
if(element=="id") {
userFacebook.set("userID", response[element]);
} else {
userFacebook.set(element, response[element]);
}
}
Thanks to Hector Ramos at Parse for helping me solve the problem! And thanks to Wayne for getting me part of the way!
Related
I am unable to accomplish a successful ReactJs using Axios Post call where the data is passed to my asp.net core 2.2 web api. The call will only successfully hit my API endpoint when all compound word (last-name) properties are hyphenated, however the data does not get through. Only single word (company) properties receive the data. I believe it is because with the hyphens the properties no longer match. However, if the properties are not hyphenated I receive a 400 error or 415 error. When sending the call via Postman, where all properties are pascal cased, I don't have any issue at all.
I have tried many things to get it to work without solutions. I have added Json Attributes to my .net object properties. I have modified the attribute to also have the hyphens. I have tried changing both my properties in my react to single word and matching them with the Json attribute, e.i created vs CreatedDate. I have also pasted into my post method the exact same json object used in my PostMancall that was successful.
.net post
[HttpPost]
[Route("AddThreshold", Name = "AddThreshold")]
public ActionResult<ThresholdDTO> AddThreshold([FromBody] ThresholdDTO threshold)
{
var thr = _thresholdService.AddThreshold(threshold);
if (thr == null)
return NoContent();
return Ok(threshold);
}
const handleAddSubmit = e => {
e.preventDefault();
let current_datetime = new Date();
let formatted_date =
current_datetime.getFullYear() +
"-" +
(current_datetime.getMonth() + 1) +
"-" +
current_datetime.getDate() +
" " +
current_datetime.getHours() +
":" +
current_datetime.getMinutes() +
":" +
current_datetime.getSeconds();
console.log(location);
let threshold = JSON.stringify({
"Threshold-Id": "",
Company: company.toString(),
"Threshold-Type": thresholdType.toString(),
"Threshold-Value": thresholdValue.toString(),
"Account-Number": account.toString(),
"Location-Number": location == "undefined" ? "" : location.toString(),
"Expected-Amount": expectedAmount.toString(),
"Created-Date": formatted_date.toString(),
"Created-By": "System",
"Updated-Date": "1900-00-00 00:00:00.000",
"Updated-By": ""
});
Axios({
method: "post",
url: "https://localhost:44394/Threshold/AddThreshold/",
data: threshold,
headers: { "Content-Type": "application/json" }
})
.then(function(response) {
//handle success
console.log(threshold);
props.handleAddClose();
})
.catch(function(response) {
//handle error
console.log(threshold);
});
};
AccountNumber: "87605177 (CenturyLink)"
Company: "Deere Employees Credit Union"
CreatedBy: "System"
CreatedDate: "2019-10-27 16:1:51"
ExpectedAmount: "90000"
LocationNumber: "5000"
ThresholdId: ""
ThresholdType: "Invoice Processing"
ThresholdValue: "10"
UpdatedBy: ""
UpdatedDate: "1900-00-00 00:00:00.000"
The above object is exactly what postman is successful with but I receive a 400 code when using axios
The problem was my UpdatedDate value did not have an format acceptable to the Json Attribute causing the whole post to fail.
I am trying to implement an Alexa Skill with Multi Turn method and a Node.js back end.
alexaApp.intent("findFact", {
"dialog": {
type: "delegate"
},
},
function(request, response) {
console.log("In Fact intent");
var test = this.event.request.intent.slots.testtwo.value;
// console.log(request.dialogState);
console.log("test fact : " + test);
response.say(get_fact());
}
);
Iam not able to get the value within the testtwo slot.
The console displays 'Unhandled exception: Cannot read property 'request' of undefined.'
Any idea why ?
Thanks !
ANSWER IS :
var test = request.data.request.intent.slots.testtwo.value;
I have an external webpage that contains only the following:-
{"date":"25 December 2017"}
Using node.js, how can I get Alexa to read (and say) the date from the webpage.
You can use "http" or "https" package in Node to do this. JSON.parse(responsestring) could easily parse the content you have shown above.
Your external webpage link would replace "yourendpoint" in below code.
var http = require("http");
http.get(yourendpoint, function (response) {
// console.log("response:" + response);
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "", data;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
if(err) {
speechOutput = "I am sorry, I could not get the data from webpage ."
} else {
console.log("response:" + buffer);
// Parse your response the way you want
speechOutput = "<<Your desired output>>"
}
}
this.emit(':tell', speechOutput);
});
});
I am using the angular fullstack generator, but I do not believe this is the problem. I am working with Stripe.js and trying to save the data to the SQLite database using Sequelize. I have tried many different things, but the server stops running when it gets to the part where it is supposed to save the data.
app.post('/register', auth.isAuthenticated(), function(req,res){
console.log('access: ',req.query)
var userId = req.body._id
var data = req.body.data
//create stripe acct for artists
stripe.accounts.create(data, function(err,acct){
if(err){
console.log('err!!! ', err)
} else {
console.log('acct: ', acct)
//look for user in database
db.User.find({
where: {
_id: userId
}
})
.then(function(user) {
if(user){
console.log('user: ', user)
//add stripe acct info to db
console.log('acct:', user.dataValues.account);
/*this is where the Server stops running*/
user.updateAttributes({
account: JSON.stringify(acct)
}).success(function(){
console.log('newacct:', user.dataValues.account);
//just to see if it works
res.send({'account': acct});
})
} else {
console.log('no user found bruh')
}
});
}
})
})
I have tried redirecting, changing req.method to 'get' and then res.redirect. res.end() all of the above, but it always stops running. No errors are thrown it just simply says 'Stopping Express Server'. Thanks in advance for the help!
I am using the $httpBackend to mock a backend and I want to get access to the headers when I have a request:
$httpBackend.whenPOST('/movies').respond(function(method, url, data) {
// How do I get access to the headers.
// I want to check the headers and retrieve a token.
var params = angular.fromJson(data),
movie = MoviesDataModel.addOne(params),
movieId = movie.id; // get the id of the new resource to populate the Location field
return [201, movie, { Location: '/movies/' + movieId }];
});
Basically, I want to check a value from the headers before I send the data.
Any ideas on how to do it?
Got this from the manual
httpBackend.whenPOST('/movies',data, function(headers){
return headers['Authorization'] == 'xxx';
})
.respond(function(method, url, data) {