Sending data from AngularJs to NodeJs issue - javascript

I'm gonna start by showing you my code
Angular Code: app.js
$scope.submit = function(){
$scope.jsonData={
"status":"OK",
"data":{
"nbOperatorPresent": $scope.nbOperatorPresent,
"objectif1stHour": $scope.objectif1stHour,
"objectif2ndHour": $scope.objectif2ndHour,
"objectif3rdHour": $scope.objectif3rdHour,
"objectif4thHour": $scope.objectif4thHour,
"objectif5thHour": $scope.objectif5thHour,
"objectif6thHour": $scope.objectif6thHour,
"objectif7thHour": $scope.objectif7thHour,
"objectif8thHour": $scope.objectif8thHour
}
}
$http.post("http://localhost:5000/settings",
JSON.stringify($scope.jsonData)).success(function(data,status){
console.log('success')
})
}
NodeJs Code: index.js
app.post('/settings',urlencodedParser,function(req,res){
console.log(req.body)
})
As you can see, I have a button to submit the data inserted by the user and send it to the server.
My problem is, when I hit submit, there is nnothing in my browser console, I mean console.log('Success !') didn't work, that is to say that all the code inner the .success(function(data,status)) won't be executed so I can't notify the user that he has submitted Successfully, I don't know where the problem came from !!
BUT In the other console console.log(req.body) I found all the data that has been passed from Angular.
Can anyone explain this to me ? I've tried other solutions but always the same problem :(

To expand on the answer...
Please note if you are unfamiliar with node and express you may want to get in the habit of returning
res.send(success: true, data: res).end()
Its very typical on the angular or UI side to be able to parse as response.data object. Just a suggestion.
and change to this:
.success(function(res,status){
console.log(res.success, res.data)
})
This is a very common architecture especially when dealing with web services that you have not control over.

You're not returning anything from the node.js code. You need to add in a returning data like:
app.post('/settings',urlencodedParser,function(req,res) {
console.log(req.body)
res.send("Success")
})

Related

JSON error in javascript when using websockets

I seem to be overlooking an error in my code that I just can't figure out. I have read multiple online sources showing what the error can be, but I can't find it in my code.
I am using WebSockets to communicate between my front and backend, when sending data in JSON format from my front to backend, it works perfectly, but not the other way around.
In my code snippets, I replaced my data with dummy values to make it easier to see the error.
Backend:
some_code.js
var msg = {"a": "a"};
Websocket.Send(msg);
websocket.js
Websocket.Send = (msg) =>
{
Websocket.Socket.clients.forEach(function each(client)
{
client.send(JSON.stringify(msg));
});
}
Frontend:
websocket.js
Socket.addEventListener("message", ({msg}) =>
{
console.log(JSON.parse(msg));
});
Error:
Any help will be appreciated, thanks!
Ok so changing the code of websocket.js to the following fixed it.
websocket.js
Socket.addEventListener("message", ({data}) =>
{
console.log(JSON.parse(data));
});
So it seems that the WebSocket library requires the variable name holding the received data to be named "data".

firebase.firestore() .set() not firing first time

I'm not a dev, I'm just learning for my own interest as a hobby.
For my own learning I'm building real world project rather than just following the usual online tutorials.
I'm building a simple vue.js app with vuex and using firebase for auth and db.
I have a method that should just take a value and .set() a new document in a collection with a single piece of data:
HTML
<template>
<div>
<v-btn #click="testing('1', '2')">Testing</v-btn>
</div>
</template>
SCRIPT
methods: {
testing(id, val) {
console.log('entered testing:', id, val)
firebase.firestore().collection('users').doc(id)
.set({
key: val
})
.then(result => {
console.log('created in firestore', result)
})
.catch(error => {
console.error('failed to create in firestore', error)
})
}
...
The problem is that after refreshing the browser the first time I click the button the method runs.
I see the console log 'entered testing' with the correct id and val but the firestore call doesn't appear to run.
Nothing in the console and no network requests.
The second time I click it I see the .then() console log 'created in firestore: undefined' and what looks like 3 network requests, and the doc and data is set correctly!
Every time I click the button after that I see the correct console log, a single network request and the doc and data is set correctly.
Other info...
I have security rules set up on the db but only basic allow if auth != null
The user is logged in when I try this.
I'm not ruling out that there might be something somewhere else in my app which is causing this but there's nothing obvious and I've stripped things right back to debug this. I'm trying to set it up so all firebase requests are done in the store only, with each component just passing it the values it needs, but to debug this I've moved all the logic (including importing firestore) into a single component.
What is going on?
Is there something obvious I'm missing?

Firebase firestore: how to query relevant documents and then update each of them

I am developing a web app on Firebase/firestore, in which users can sign in and write their own posts. The data are stored in the following way:
-User information are stored as under collection('user').doc('uid').
-Information about posts the user has written are stored in collection('post').doc('postid'), and the doc has 'userinfo' and 'uid' fields. The 'userinfo' field contains exact copy of what is stored in 'uid' doc, just in object format.
Here are the operations that I want to do:
When the user changes the data, the changes are reflected in the document.
Look for the all the posts that the user has written based on 'uid' data, and then update userinfo in those data.
The last part is tricky for me. The Firebase documentations cover situations where the references are pretty much static, i.e. you know the exact path to write/update. What I am trying to do is look for a set of documents that is not necessarily static, and then update each of them.
Here is the code I wrote for this effort. The first part works without any problem. Of course, the second part doesn't work. :) What would be the code to do the do the second part?
const update = () => {
//This part is for updating user information. This works without any problem.
firebase.firestore().collection('user').doc(user.uid).update({
username: username1,
nickname: nickname1,
intro: intro1
})
.then(()=>{
//This part is for updating all of the document that the user has written based on 'uid' value. This doesn't work.
//Below code is probably way off, but it shows where I am going and what I am trying to do.
firebase.firestore().collection('post').where('uid','==',user.uid).get()
.then((querysnapshot)=>{
querysnapshot.forEach((doc)=>{
let ref=firebase.firestore().collection('post').doc(doc.id);
ref.update({
userinfo: {nickname:nickname1,username:username1,intro:intro1}
})
})
})
}).then(()=>{
alert("Successfully updated!");
window.location.href='/'+username1;
}).catch((error)=>{
alert("Error!");
})
}
Thanks a lot in advance!
What's the error that you get running this code? It seems on the right track for me.
But despite that, here are some suggestions to deal with this kind of update:
Don't do the second part on the client side, do it on the server side with a Firestore Trigger (create a onUpdate trigger in the user collection in your case): https://firebase.google.com/docs/functions/firestore-events.
The problem of doing in the client side, is because if the user closes the page/browser or the site goes offline in the middle of the update, you will have inconsistent data.
You don't need to recreate the DocumentReference after getting the query result, the docs returned already have a .ref that you can call .ref.update() directly.
EDIT: If you want to keep your original code (updating on client side), the problem of the navigation occurring before all the updates to conclude is because ref.update() returns a promise.
So the update queue is asynchronous being performed on database when the client navigates away.
To solve this, I would use a Promise.all() to wait all updates being completed.
firebase.firestore().collection('post').where('uid','==',user.uid).get()
.then((querysnapshot)=>{
const promises = [];
querysnapshot.forEach((doc)=>{
promises.push(doc.ref.update({
userinfo: {nickname:nickname1,username:username1,intro:intro1}
});
});
Promise.all(promises).then(()=>{window.location.href='/'+username1;});
});
Or using the await syntax (I think it's easier to maintain and understand):
const querysnapshot = await firebase.firestore().collection('post').where('uid','==',user.uid).get();
const promises = [];
querysnapshot.forEach((doc)=>{
promises.push(doc.ref.update({
userinfo: {nickname:nickname1,username:username1,intro:intro1}
});
});
await Promise.all(promises);
window.location.href='/'+username1;

Ionic Push User identification issue

I'm having this issue where I register for Push using $ionicPush.register() But I'm not doing user identification at any point using $ionicUser(like the docs suggest). So, I'm only calling $ionicPush.register() and I wait for that promise to resolve and I'm storing the device_token on my server, eg.
$ionicPush.register({
onNotification: function(notification) {
//....
}
}).then(function(deviceToken) {
//Save device-token to my server
UserService.saveIosDeviceToken(user.id, deviceToken)
.then(function(user) {
return user;
})
.catch(function(error) {
console.log(error);
});
});
I have noticed that regardless of calling $ionicUser.identify(...) or not, an $ionicUser will be created (which you can see in the Dashboard). Now the issue that I'm having is that I'm not always getting a device token. ie. I end up with some(not all) Ionic Users with no device tokens (therefore no device token I can store on my server), eg.
Do you guys know what's going on? I'm reading the FAQ here and it says: > "If you are using $ionicPush.register() without passing a user object, you should make sure you are waiting for the $ionicPush.identify() promise to complete." -- Could this be the likely cause? and How do I pass a user to $ionicPush.register()?
Let me know what you guys think, I really need to know what I'm doing wrong.
Regards,
-J

Get _id after Accounts.createUser

I'm trying to create a new user and use their _id for another collection right after it's created.
var newUserId = Accounts.createUser({username: "w/e", password:"w/e"});
doesn't work as I thought.
I know if you insert something into a collection it returns the _id, so I'd assume this would be same, but apparently it's not.
"newUserId" ends up being undefined.
I'm not sure if this matter, but I'm creating the user via server side.
Any helps is appreciated, thanks.
*Solved:
Got the code to do what it needed to do.
Accounts.validateNewUser(function (user){
//do something after user creation
});
slap that code into the account.js in the server side.
Once the user was created via
Accounts.createUser({})
the method:
Account.validateNewUser()
fire immediately afterward. Used the user argument to get whatever the new user properties I need (in this case the _id and username) and plugged that into another collection meteor method.
Thanks again!
PS: turns out
Accounts.createUser({})
Actually does return the _id, but you can only see it in the server console, but not the client console, so I apologize for any confusion. That was my mistake.
To debug this, specify a callback then look at the error that is being returned.
Accounts.createUser({username: "w/e", password: "w/e", function(err){
if ( err ) console.log(err);
}

Categories