HTTP post from angularjs controller to Nodejs - javascript

This is my angular controller code
clientApp.controller('formCtrl',function($scope,$http){
$scope.statuses = ["Active", "Inactive"];
$scope.cluster = ["East Coast","West Coast","PayPal"]
//when submit button is clicked
$scope.submit = function() {
alert("Submit Clicked");
$http.post('/clientPost', $scope.formData).success(function(response) {
console.log('Data posted successfully');
})
.error(function(data){
console.log('Error: ' + data);
});
};
});
This code takes a set of values from the frontend form in $scope.formData and is trying to pass it on to the backend nodejs file using $http.post..
Node js - server side controller
app.post('/clientPost', function(req, res) {
alert("Posted successfully");
var cope = req.body.params;
var query = "insert into lv_billing.client (Client_ID, Client_Name, Status, Updt_Time, Updt_By, Updt_ID, Cluster) values ?"
alert(cope);
});
However, i m unable to connect to the nodejs

Related

like & Dislike button node JS mongodb

I'm trying to build a system for like & dislike posts in my project but I'm facing some issue using this on the client side , I have this form
but the problem there is no communication between server and client I don't know what I'm missing, even I click on like button I see in the client side value 1 but nothing happen on server side
the front is build with EJS view engine and this my code
<div class="row">
<button onclick="actOnPost(event);"
data-post-id="<%= user.posts[x].id %>">Like
</button>
<span id="likes-count-<%= user.posts[x].id %>"><%= user.posts[x].likes %></span>
</div>
I use this script in the index.ejs file :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var updatePostStats = {
Like: function (postId) {
document.querySelector('#likes-count-' + postId).textContent++;
},
Unlike: function(postId) {
document.querySelector('#likes-count-' + postId).textContent--;
}
};
var toggleButtonText = {
Like: function(button) {
button.textContent = "Unlike";
},
Unlike: function(button) {
button.textContent = "Like";
}
};
var actOnPost = function (event) {
var postId = event.target.dataset.postId;
var action = event.target.textContent.trim();
toggleButtonText[action](event.target);
updatePostStats[action](postId);
axios.post('/posts/' + postId + '/act', { action: action });
};
</script>
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
var pusher = new Pusher('your-app-id', {
cluster: 'your-app-cluster'
});
var socketId;
// retrieve the socket ID on successful connection
pusher.connection.bind('connected', function() {
socketId = pusher.connection.socket_id;
});
var channel = pusher.subscribe('post-events');
channel.bind('postAction', function(data) {
// log message data to console - for debugging purposes
console.log(data);
var action = data.action;
updatePostStats[action](data.postId);
});
</script>
for the server side I have this code located in file.js:
router.post('/posts/:id/act', (req, res, next) => {
console.log('im here')
const action = req.body.action;
const counter = action === 'Like' ? 1 : -1;
Post.update({_id: req.params.id}, {$inc: {likes_count: counter}}, {}, (err, numberAffected) => {
pusher.trigger('post-events', 'postAction', { action: action, postId: req.params.id }, req.body.socketId);
res.send('');
});
});
I added console.log('Im here') to verify if there something is launching on my server side but I don't get anything, this router is not even launched
my mongodb image for posts and like button is below :
could it be possible to help on solving this or provide me a better exemple to follow ?
Best Regards,
Instead of making string or number in like, make an array, push req.user.id- user-id of the particular logged in user, and get the array length. This will give you total number of likes. In order to get toggle functionality, search that user id using findOne method and if no user found, push the id of the user who clicked the like button else pull the user id of the same user. Always print the length of the array so that while performing push or pull operations, you will get real time length of the like array.

printing a variable into a div

I am atempting to build a chatroom with NodeJS and Socket.io and I have gotten so far as to get the users input and send it to the Node server but that's all I want to be able to display it up in a div
Client-side script
var socket = io();
$('form').submit(function(e) {
e.preventDefault();
// gets the value from the message text feild and sets it as the message var
var message = {
text: $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
}
$('#chat-box-div-txtinpt').focus();
document.getElementById('chat-box-div-txtinpt').value='';
});
Server-side script
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconected');
});
socket.on('chat-message', function (message) {
console.log('message: ' + message.text);
});
});
Here is the site
It appears you're using jQuery, so for this line: document.getElementById('chat-box-div-txtinpt').value=''; you could just do $('#chat-box-div-txtinpt').val('');
to answer your question: you could just do $('#chatlog-display-div').append(message.text)
Your code would end up looking something like this
$('form').submit(function(e) {
e.preventDefault();
//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
//append the message to the chatlog-display-div
$('#chatlog-display-div').append(message.text);
}
//clear the value of the txtinput after you focus it.
$('#chat-box-div-txtinpt').focus().val('');
});
please mark as accepted answer if you feel this adequately solves the issue.
To send messages to everyone from the server use emit() from io
on server
socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
io.emit("chat-message",message);
});
on client
socket.on('chat-message',function(message){
//add message to the chat window
});
If you do not want the person sending the message to get the chat-message emit then use broadcast.emit() from the socket that sent it
//server
socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
//excludes "socket" from getting the emit
socket.broadcast.emit("chat-message",message);
});
To actually put the message in the div just use any of jQuery's various methods html()/text()/append()
//client
socket.on('chat-message', function (message) {
jQuery(".chat-window").append('<div>'+message.text+'</div>');
});
You could simple .append the text to "chatlog-display-div" with a templet if you use ES6 could be something like
$('form').submit(function(e) {
e.preventDefault();
//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message', message);
document.getElementById('chatlog-display-div').append('<divclass="message-style" > ${message.text}</div>')
}
$('#chat-box-div-txtinpt').focus();
document.getElementById('chat-box-div-txtinpt').value='';
});

How do I receive and use a JSON object on the client-side from the server (Node JS and Express)?

I am trying to do something seemingly very simple but I'm having trouble working it out. Users can submit some text using a HTML form with POST method. This is then sent off to an API for processing, and returns with a JSON object. I then just want the app.js file to send this JSON object back so I can play around with it using JQuery.
Here is the .post method in my app.js
app.post('/', function(req, res){
console.log("starting app.post");
// See User Modeling API docs. Path to profile analysis is /api/v2/profile
// remove the last / from service_url if exist
var parts = url.parse(service_url.replace(/\/$/,''));
var profile_options = { host: parts.hostname,
port: parts.port,
path: parts.pathname + "/api/v2/profile",
method: 'POST',
headers: {
'Content-Type' :'application/json',
'Authorization' : auth }
};
// create a profile request with the text and the https options and call it
create_profile_request(profile_options,req.body.content)(function(error,profile_string) {
if (error) {res.render('home.html',{'error': error.message});
console.log("errormessage: "+error.message);
}
else {
// parse the profile and format it
var profile_json = JSON.parse(profile_string);
var flat_traits = flatten.flat(profile_json.tree);
// Extend the profile options and change the request path to get the visualization
var fileName="file 1"; //this will eventually be imported automatically
//console.log(flat_traits);
var scoreObject={"title":fileName, "percentage":functions.matchPercentage(flat_traits)}
res.send(scoreObject); //this is what I assume should send this back client-side
});
}
});
});
// creates a request function using the https options and the text in content
// the function that return receives a callback
var create_profile_request = function(options,content) {
return function (/*function*/ callback) {
// create the post data to send to the User Modeling service
var post_data = {
'contentItems' : [{
'userid' : 'dummy',
'id' : 'dummyUuid',
'sourceid' : 'freetext',
'contenttype' : 'text/plain',
'language' : 'en',
'content': content
}]
};
// Create a request to POST to the User Modeling service
var profile_req = https.request(options, function(result) {
result.setEncoding('utf-8');
var response_string = '';
result.on('data', function(chunk) {
response_string += chunk;
});
result.on('end', function() {
if (result.statusCode != 200) {
var error = JSON.parse(response_string);
console.log("status: "+result.statusCode);
callback({'message': error.user_message}, null);
console.log(error.user_message);
} else
callback(null,response_string);
});
});
profile_req.on('error', function(e) {
callback(e,null);
});
profile_req.write(JSON.stringify(post_data));
profile_req.end();
}
};
So I presume res.send is what passes the data across to the client-side, but then how do I receive the data on the client-side? This is my attempt at the JScript:
$.getJSON('/').done(function(data){
$('#resultsList').append('<li data-icon="arrow-r" data-iconpos="right" id="'+
data.title+'"> <a href="#breakdownDialog"> <div id="cvResults"><h3>'+
data.title+'</h3> <span>'+data.percentage+
'%</span></div></a><div id="output"></div></li>');
console.log(data.title+data.percentage);
}
});
I want to take some of the values from the JSON object and put them in a list on the existing HTML page. At the moment this just takes me to a different blank page that says Undefined.
How should I grab the JSON data from the server?
EDIT: Here's the HTML form I am submitting the data with:
<form method="POST" id="submitForm">
<fieldset>
<textarea id="textArea" required="true" rows="5" name="content"></textarea>
<button class="btn btn-block" type="submit">
Analyse
</button>
</fieldset>
</form>
Are you sure that you are sending json with res.send()? Try to set header
res.set('Content-Type', 'application/json') or use this res.json() instead of res.send()

node, socket.io - update client when new entry added to news feed?

I've created client and server of node with socket.io. server is executing 4 get requests of news feed and fetched the data. These data is sent to the client with socket.io.
client is displaying news feed on the occurrence of specific socket.io event.
This works well for once. Here is the code and working fiddle
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, redis = require("redis");
var http = require("http");
// initialize the container for our data
var data = "";
var nfs = [
"http://economictimes.feedsportal.com/c/33041/f/534037/index.rss",
"http://www.timesonline.co.uk/tol/feeds/rss/uknews.xml",
"http://www.independent.co.uk/news/business/rss",
"http://www.dailymail.co.uk/money/index.rss"
];
//setInterval(function() {
for(var i=0; i<nfs.length; i++){
//console.log(nfs[i]);
http.get(nfs[i], function (http_res) {
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log("data received");
});
});
}
//}, 30000);
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
//setInterval(function() {
socket.emit('news', data);
/*socket.on('my other event', function (data) {
console.log(data);
});*/
//}, 5000);
});
client.html
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
//socket io client
var socket = io.connect('http://localhost:8080');
//on connetion, updates connection state and sends subscribe request
socket.on('connect', function(data){
setStatus('connected');
socket.emit('subscribe', {channel:'notif'});
});
//when reconnection is attempted, updates status
socket.on('reconnecting', function(data){
setStatus('reconnecting');
});
//on new message adds a new message to display
socket.on('news', function (data) {
console.log(data);
//socket.emit('my other event', { my: 'data' });
addMessage(data);
});
/*socket.on('news', function (data) {
debugger;
socket.emit('my other event', { my: 'data' }
var msg = "";
if (data) {
msg = data;
}
addMessage(msg);
});*/
//updates status to the status div
function setStatus(msg) {
$('#status').html('Connection Status : ' + msg);
}
//adds message to messages div
function addMessage(msg) {
//debugger;
var $xml = $(msg);
var html = '';
$xml.find("item").each(function() {
var $item = $(this);
html += '<li>' +
'<h3><a href ="' + $item.find("link").text() + '" target="_new">' +
$item.find("title").text() + '</a></h3> ' +
'<p>' + $item.find("description").text() + '</p>' +
// '<p>' + $item.attr("c:date") + '</p>' +
'</li>';
});
$('#result').prepend(html);
}
</script>
</head>
<body>
<div id="status"></div><br><br>
<ul id="result"></ul>
</body>
</html>
What I understand about socket.io is that we don't need long server polling and so how do server come to know that news is added to the respected news feed.
How do I update the client with newly added news when news is added to the news feed rss ???
Update
Ok so from all the responses I get the point that it is not possible for socket.io to know that new entry has been added. So, how do I know (which tools/libraries do require to know that new entry has beed added and update the client as well) ???
Retrieving the messages from the news feeds are completely independent of socket.io unless the news feeds implement sockets on their end and your server becomes their client. So you will have to continue to poll them with http requests to know whether they have updated data.
In order to notify your clients of the update you would just emit the news event. Presumably you would have logic on the server to make sure you are only sending events which have not previously be sent.
There is no way for "node" to know when a new entry is added to the news feed. You will have to poll the news service like you are doing now. This really has nothing to do with Node or Socket.io unless I completely misunderstand what you are asking.

Node JS and ajax problems

I am trying to receive data through ajax from node.js but I am not sure what I am doing wrong between interacting the two.
Here is my ajax get request:
$.get('/notificationsNumber',
function (notify) {
alert(notify);
$('.notifications').html("Notifications " + 0).css("color","red")
});
Here is my node.js file:
exports.notificationsNumber = function(req, res) {
console.log('notifying start');
Friend.findOne({userId: req.signedCookies.userid}, function(err,user) {
if(err) {
res.send(err);
console.log('notifying err');
} else {
console.log('notifying');
console.log(user.notifications);
var notify = user.notifications;
console.log(notify);
res.send(notify);
}
});
};
UPDATE:
app.get('/notificationsNumber', user.notificationsNumber);
Here is the app.js code:
The alert is popping up the html doc of the page for some reason... and the line underneath it actually works correctly. Trying to connect the notify (which on the server side prints out the correct data).
Ok I was doing it as res.send it should be res.json...

Categories