How to access Angular Js data from nodejs - javascript

Hi in my angular js file, I have patient objects which contain name, number and appointment date. In my node js file, I use twilio to send a text a patient. What I want to know is how to get the number from the angular js file in order to use it in my node Js file so I can send the patient a text. Thanks.
here is the part of server.js where I send the text message
app.post('/testtwilio', function(req,res){
var cheerio = require('cheerio'),
$ = cheerio.load('file.html'),
fs = require('fs');
fs.readFile('./views/index.html', function (err, html) {
if (err) {
throw err;
} else {
$ = cheerio.load(html.toString());
console.log($scope.patients)//$('.reminder').attr('text'));
}
});
client.sendMessage({
to: '{{patient.number}}',
from: '+16173935460',
body: 'Text sent using NodeJS'
}, function(err, data){
if(err)
console.log(err);
});
})
Here is the patient object in the MainController.js
$scope.patients = [
{
name: 'John Smith',
date: "12/22/2016",
number: 1829191844
},
{
name: 'Matt',
date: "09/15/2016",
number: 1829198344
},
{
name: 'John',
date: "08/25/2016",
number: 1829198844
},
];

Pass the data from the front end to the backend? Have angular call a route on your backend with the data you need and access it with the req.params object.
Is your server.js a node.js controller?
In the angular controller you could import $http and just do a $http.post({myparams}, /myRoute, function(results){console.log(results)})
Like Mike says. The only way to really share files between the front end and the backend is if the files are JSON as that can be read by Angular and Node. However, I usually just use this for static configuration files.

Related

Failed to append data in .json file using node

I want to append my data which is array of object format to the existing .json file so I have written code for it, but on stackoverflow I noticed so many developers suggesting before appending to existing json file first read file and then push new data to existing json file. So I followed this and made changes according to this but getting error :
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
Code written in node
newdata=[
{
UserId: '11',
UserName: 'harry',
},
{
UserId: 12,
UserName: 'David',
}
];
fs.readFile('results.json', function (err, data) {
if(data === '') {
json = JSON.parse(newdata);
json.push(newdata);
}
fs.writeFile("results.json", JSON.stringify(json));
})
This error is because you are using the .writeFile in a wrong way.
Try something like this:
fs.writeFile('results.json', JSON.stringify(newData), function(err) {
if (err) throw err;
});
A short explanation:
The ERR_INVALID_CALLBACK in the error message is the missing of the function informed in the last parameter in the example above.
fs.writeFile(<file>, <content>, <callback>)

How to update clients when database is edited outside of feathersjs app

I have two server-side applications editing the same database.
One server is a feathersjs app and another is a simple nodejs app. A frontend app connects to the feathersjs app via feathersjs client.
How, when the nodejs app edits the database, can I update clients connected to the feathersjs app? As currently any changes made outside the featherjs app aren't reflected on the feathersjs clients.
Can I trigger the patched event somehow and force the clients to pull down the updated data?
if you are using mongodb with WiredTiger storageEngine you can use the collection.watch() function and add a monitor in your feathers app something like this
//src/services/monitor.js
module.exports = function(app){
//get mongo client
const mongoClient = app.get('mongoClient');
//connect db
mongoClient.then(db => {
//collection to watch
const collection = db.collection('your_collection_name')
//watch collection
const changeStream = collection.watch({ fullDocument: 'updateLookup' });
//on some data changed
changeStream.on('change', data => {
console.log ( 'something is changed in your collection' , data )
//your service.emit
});
})
}
Then I added this simple monitor in the /src/services/index.js (maybe not the right way but it works)
//src/services/index.js
...
const monitor = require('./monitor.js');
module.exports = function (app) {
...
app.configure(monitor);
...
};
Data returned on every change on the collection
{ _id:
{ _data:
'825C7F03230000001C29295A100490DEF2C65812410FABF0DE46F9C89D7246645F696400645C1AC097B189CBD5D4A24D330004' },
operationType: 'replace',
clusterTime:
Timestamp { _bsontype: 'Timestamp', low_: 28, high_: 1551827747 },
fullDocument:
{ _id: 5c1ac097b189cbd5d4a24d33,
id: '12',
language: 'it-IT',
category: 'some data',
slug: '',
description: 'some data',
src:'',
color: 'card',
status: true,
home: true,
order_int: '3',
visual: 'card' },
ns: { db: 'mydb', coll: 'mycollection' },
documentKey: { _id: 5c1ac097b189cbd5d4a24d33 } }
More info here https://docs.mongodb.com/manual/reference/method/db.collection.watch/
As you pointed out, only changes made through the Feathers API will be reflected but on the server you can always emit the event you need via service.emit:
dbConnection.on('someDatabaseUpdate', data => {
app.service('messages').emit('patched', data);
app.service('messages').emit('updated', data);
});
Things to note here (also discussed in this issue):
There will be no user or any other information about the method call
data will not be run through any service hooks

How can you programmatically create a user in a Cognito User Pool?

The AWS documentation indicates that it is possible for an admin to create a user pool user in AWS Cognito using the API.
Here is the documentation I am referring to: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html
However the documentation provides scant details and not even an example of how this is done. It makes no mention of what endpoint to call, what SDK function to use, or anything regarding authentication, etc.
Does anyone have experience creating new users directly from your code ?
It's actually quite easy if you follow the development documentation (https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html), more specifically the "signUp" function.
From the Docs:
var params = {
ClientId: 'STRING_VALUE', /* required */
Password: 'STRING_VALUE', /* required */
Username: 'STRING_VALUE', /* required */
AnalyticsMetadata: {
AnalyticsEndpointId: 'STRING_VALUE'
},
SecretHash: 'STRING_VALUE',
UserAttributes: [
{
Name: 'STRING_VALUE', /* required */
Value: 'STRING_VALUE'
},
/* more items */
],
UserContextData: {
EncodedData: 'STRING_VALUE'
},
ValidationData: [
{
Name: 'STRING_VALUE', /* required */
Value: 'STRING_VALUE'
},
/* more items */
]
};
cognitoidentityserviceprovider.signUp(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
And using this, it's simple to create a user (example in Lambda, but can easily be modified as JS on its own):
'use strict'
var AWS = require('aws-sdk');
var resp200ok = { statusCode: 200, headers: {'Content-Type': 'application/json'}, body: {} };
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
// ^ Hard to find that this is the way to import the library, but it was obvious in docs
exports.handler = function(event, context, callback){
var params = {
ClientId: 'the App Client you set up with your identity pool (usually 26 alphanum chars)',
Password: 'the password you want the user to have (keep in mind the password restrictions you set when creating pool)',
Username: 'the username you want the user to have',
UserAttributes:[ {
{
Name: 'name',
Value: 'Private'
},
{
Name: 'family_name',
Value: 'Not-Tellinglol'
},
}],
};
cognitoidentityserviceprovider.signUp(params, function(err, data) {
if (err){ console.log(err, err.stack); }
else{ resp200ok.body = JSON.stringify(data); callback(null, resp200ok); }
});
};
Anything you set to required in your Cognito pool setup has to be in the UserAttributes section (usually the email is defaulted to required, check if yours is). The list of things you can assign values to is found in (Cognito pool) General Settings -> App Clients -> Show Details -> Set Read/Write -> (list of things), here you can add custom attributes (like if you want to specify what city your user is from, or if you want to add whatever else (String/Number)).
When assigning a value to a custom field, your "Name" in the UserAttributes will be "custom:whatever", so if the custom field is "city" the Name is "custom:city".
Hopefully I wasn't stating too much of the obvious, but these are things it took me a while to figure out with the broken up SO info, and AWS docs, and I figured I'd plop it all together.
Here is an example using python/Flask
import traceback
import boto3
from flask import Flask, render_template, request
app = Flask(__name__)
def cognito_register_user(email):
print("sign up user: ", email)
try:
aws_client = boto3.client('cognito-idp', region_name = "us-west-2",)
response = aws_client.admin_create_user(UserPoolId="us-west-2_sdfgsdfgsdfg",Username=email,UserAttributes=[{"Name": "email","Value": email},{ "Name": "email_verified", "Value": "true" }],DesiredDeliveryMediums=['EMAIL'])
print("response=", response)
return response
except:
traceback.print_exc()
return None
#app.route('/')
def root():
return render_template('register_email.html', title='register mail')
#app.route('/register/email', methods=['POST'])
def sign_up():
if request.method == 'POST':
email = request.form['email']
print("email=", email)
cognito_register_user(email)
return render_template('register_email_complete.html', title='flask test', email=email)
if __name__ == "__main__":
app.run(debug=True)

How to convert a template from jade to HBS?

I am not too familiar with the jade template language, but quite familiar with handle bars. I need to use hbs because my project is based on hbs.
I have the following the braintree payment for nodejs express, and their view was based on jade.
https://github.com/braintree/braintree_express_example/blob/master/views/checkouts/new.jade
form#payment-form(action="/checkouts", method="post")
section
.bt-drop-in-wrapper
#bt-dropin
label(for="amount")
span.input-label Amount
.input-wrapper.amount-wrapper
input#amount(name="amount" type="tel" min="1" placeholder="Amount" value="10")
button.button(type="submit")
span Test Transaction
script(src="https://js.braintreegateway.com/js/braintree-2.27.0.min.js")
script.
(function () {
var checkout = new Demo({
formID: 'payment-form'
});
var token = "#{clientToken}";
braintree.setup(token, "dropin", {
container: "bt-dropin"
});
Below is my router
router.post('/', parseUrlEnconded, function (request, response) {
var transaction = request.body;
gateway.transaction.sale({
amount: 7,
paymentMethodNonce: transaction.payment_method_nonce
}, function (err, result) {
if (err) throw err;
if (result.success) {
[...]
I essentially want the payment form to be shown in view, and the payment_method_nonce value submitted to the server
Use jade-to-handlebars, which is a nodejs module to do exactly what you ask.

Array of Objects not being received as an Array node.js

I am passing a POST that includes an array of "wines". The object on the send looks line. However when I log the request on the server side, the array is a collection of keys and values. What am I missing:
**** MY TEST REQUESTING CODE ****
request.post("http://localhost:3000/todos", {form: params}, function(err, response){
console.log(response.body);
})
**** THE OPTION AS IT IS BEING SENT ****
var params = {
name: 'Test Do',
summary: 'This is the summary',
wines: ['56ad66897070ffc5387352dc', '56dg66898180ffd6487353ef']
}
**** MY SERVER SIDE CODE --- SHORTEN FOR BREVITY ***
exports.todoPost = function(req, res){
console.log(req.body);
var todo = new ToDo(req.body);
todo.save(function(err, todoX){
if(err){return res.send.err;}
console.log(req.body.store_config)
if(todo.wines){
**** THE OUTPUT OF 'console.log(req.body) ****
{ name: 'Test Do',
summary: 'This is the summary',
'wines[0]': '56ad66897070ffc5387352dc',
'wines[1]': '56dg66898180ffd6487353ef' }
Can I not send an array in a POST? Everything I see online and everything I've tried isn't working. It says I'm passing stuff correctly.
Technically you did send an array using POST. They're just handled differently. One thing you could do instead is send the object as a JSON string.
request.post("...", { form: JSON.stringify(params) }, function( ...
Then on the server-side, just undo the stringifying by using JSON.parse.
var params = JSON.parse(req.body);

Categories

Resources