Update UI in real time with angular and express - javascript

I have two UIs, one for order.html and one for ledger.html running on two different ports 3000 and 8000 on localhost . On the order page, a user can place an order for an item. Once he places the order, the information is sent as a POST request to server on port 8000.
Below is the post request from the order.html page to server with port 8000
$scope.sendPostRequest=function(){
var dataToBeSent = $scope.postData;
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/receiveOrder',
headers: { 'Content-Type': 'text/plain' },
data: 'some random data'
}).then(function successCallback(response) {
//extracts key:value pairs from the json sent back
$scope.postResponse= someResponse
}, function errorCallback(error) {
// some error handler functions here
})
}
Below is the express code at port 8000 to receive the above request.
app.post('/receiveOrder', function(req, res){
console.log('type of request '+Type(req));
//extract the text passed in data section of the post request
//TODO: Use the data received to update the dashboard, ledger.html
//send some response back as confirmation
});
Once the POST request is received and the data sent is parsed using body-parser, I need to update the UI of ledger.html page to show this.
Basically, ledger.html keeps track of the orders placed by users in real time. It is a dashboard in which fresh orders keep getting added as they are placed. I am stuck in achieving the above.
I have experimented with using socket.io by way of using event-emitters but could not go very far. I have a schema setup for the order data in MongoDB as well in case I need it.
May I have some guidance about what I can use to achieve the above.

Related

Node.js - How to send sessionID to GET method in Express via request package? [duplicate]

I'm trying to use NodeJS to scrape a website that requires a login by POST.
Then once I'm logged in I can access a separate webpage by GET.
The first problem right now is logging in. I've tried to use request to POST the login information, but the response I get does not appear to be logged in.
exports.getstats = function (req, res) {
request.post({url : requesturl, form: lform}, function(err, response, body) {
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(body);
res.end();
});
};
Here I'm just forwarding the page I get back, but the page I get back still shows the login form, and if I try to access another page it says I'm not logged in.
I think I need to maintain the client side session and cookie data, but I can find no resources to help me understand how to do that.
As a followup I ended up using zombiejs to get the functionality I needed
You need to make a cookie jar and use the same jar for all related requests.
var cookieJar = request.jar();
request.post({url : requesturl, jar: cookieJar, form: lform}, ...
That should in theory allow you to scrape pages with GET as a logged-in user, but only once you get the actual login code working. Based on your description of the response to your login POST, that may not be actually working correctly yet, so the cookie jar won't help until you fix the problems in your login code first.
The request.jar(); didn't work for me. So I am using the headers response to make another request like this:
request.post({
url: 'https://exampleurl.com/login',
form: {"login":"xxxx", "password":"xxxx"}
}, function(error, response, body){
request.get({
url:"https://exampleurl.com/logged",
header: response.headers
},function(error, response, body){
// The full html of the authenticated page
console.log(body);
});
});
Actualy this way is working fine. =D
Request manages cookies between requests if you enable it:
Cookies are disabled by default (else, they would be used in
subsequent requests). To enable cookies, set jar to true (either in
defaults or options).
const request = request.defaults({jar: true})
request('http://www.google.com', function () {
request('http://images.google.com')
});

why does expressjs generate ERR_EMPTY_RESPONSE for PUT when idle?

Currently
I have an express server that I am running locally to manage requests from a react client.
Problem
When my client is idle (I assume after the client PUT server actions previously), after about 3-5mins, error messages appear in the console logs.
Error Message:
This causes the next client PUT to the server to fail i.e. data is not saved.
Request
I don't have much experience with middleware management, so would appreciate some help on how to diagnose what may be causing this error.
Notes that may be helpful:
sometimes when the client makes too many PUTs to the server, the data fails to save, but there is no error message. I am forced to reload the page.
Extract from Client - App.js
saveData = data => {
console.log("Submitting request to save...");
fetch('/api/v1/savedata', {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(console.log("Save complete!"));
};
Extract from Server.js:
// An api endpoint that saves data from the client
app.put('/api/v1/savedata', (req,res) => {
console.log('Server received request to saveData');
let options = {
files: './data/save.json',
changes: req.body
}
updateJsonFile(options);
});
you didn't sent any response in the API, use res.send or res.json like this:
app.put('/api/v1/savedata', (req,res) => {
console.log('Server received request to saveData');
let options = {
files: './data/save.json',
changes: req.body
}
updateJsonFile(options);
res.json({data: data}) // if you want to send json response
// Note: please don't send response object more than once
});

Angularjs $http Service POST, PUT and GET

I am developing application in AngularJS. But I still not so clear the difference of POST, PUT and GET. Usually I use $http GET when I get data from server when server side does not require any front end data to return data to client side as below.
$http.get(configSettings.baseUrl +"retrive_user.php").success(function (data) {
}).error(function() {
console.log("error");
});
When I am using POST is when I server side require front end data in order to return data to client side as following.
$http({
url: configSettings.baseUrl + "insert_message.php",
method: "POST",
data: {
'username': username,
'messageContent' : messsageContent,
'sender_id': usernameID,
'subscribeChannel' : subscribeChannel,
'attachmentType' : attachmentType,
'event' : 'chat_message'
}
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
})
});
Even, I want to delete data or edit data in my MySQL database I am using POST method in angularjs as above and then in my PHP server side, I do like following to get data.
$chat_info = file_get_contents("php://input");
$chat_request = json_decode($chat_info,true);
#$username = $chat_request['username'];
#$messageContent = $chat_request['messageContent'];
#$sender_id = $chat_request['sender_id'];
#$subscribeChannel = $chat_request['subscribeChannel'];
#$attachmentType = $chat_request['attachmentType'];
#$event = $chat_request['event'];
I don't know whether this is a correct practice in RESTful API. I understand the difference between POST and GET. I my server side scripting, I just need to get data from client side in order to Create, Update, Read and Delete data from database. What so special about PUT, DELETE and PATCH in RESTful API?
HTTP verbs are probably one of the most cryptic things about the HTTP protocol.
PUT replace the ENTIRE RESOURCE with the new representation provided or you can say that if user want to add new record, he should use PUT.
On the other hand PATCH => As the name said its a kind of patch to update a piece of record. If user can only wants to update a partial record, say just an email address, he should use PATCH.
As PUT method can update all the record so it need more bandwidth or handle full resources instead on
partial. So PATCH was introduced to reduce the bandwidth.
For example :- lets say I am sending new record to server i.e,
{ "first": "Anand Deep", "last": "Singh" }
So I will use Put because I am adding new record. But here has one problem with Put request that when I will use PUT, I have to send all two parameters that is first and last again. so it is mandatory to send all value again
But Patch only send the data which user want to update and it won't effecting or changing other data.So no need to send all value again.
So PUT for creating new record and PATCH is for updating existing record.
Same for DELETE, its tell to server that this request should delete the record which pass it to server.
For more details click on below image or this URL :-

Ajax request not working in loopback

I am beginner in loopback and working on Get Post in loopback
This is code on client side
var datas = 'Something';
$.ajax({
type: 'POST',
url: '/post',
data: datas,
dataType: 'text'
})
.done(function(data) {
console.log('Successful');
.fail(function(jqXhr) {
console.log('Failed');
});
and this is on server side(server.js)
app.post('/post', function(req, res){
console.log('This is DATA '+ req.body);
});
This is not working it gives me 404 not found or failed.
What am I doing wrong and Is there another method for get post in loopback?
the server side needs an server and listening a port.
the client side needs to listen another port.
so they are not in one domain and cannot get access to each other.
this called a "cross-origin requests"
check this for the solution:https://www.w3.org/TR/cors/
Your URL starts with '/'.
Whenever a URL starts with '/' it is treated as absolute URL.
Whereas, most of the time, web apps are bounded with a context root.
Try using URL without initial '/' and it should work.

How to receive a nodejs data response from ajax

I am currently learning express, ajax, and nodejs. So currently I am trying to make ajax and nodejs interact with each other. I am sending a client request, using ajax, to a nodejs server. Currently, I am able to invoke app.get in the server correctly, i.e. it works fine until the call to console.log(req.query); at the server side. However, I am having trouble accepting data, that is sent by the server. The client side code does not alert any returned data as I tried to make it to.
This is my code on the client side.
function login(){
var obj = '{"username":"'+$('#username').val()+'", "password":"'+$('#password').val()+'"}';
$.ajax({
type:'GET',
dataType :'json',
data:{"username": $("#username").val(),
"password": $("#password").val()},
url:'http://localhost:10351/function',
success: function (data) {
alert("ajax callaback response:"+JSON.stringify(data));
}
})
This is my code on the server side.
var express = require('express');
var app = express();
var http = require("http");
var server = http.createServer();
var portNumber = 10351;
app.use(express.static('public'));
app.get('/function', function(req, res) {
console.log(req.query);
res.send(JSON.stringify(req.query));
});
app.listen(portNumber, function() {
console.log('Currently listening on port ' + portNumber);
});
Any tips?
I was looking at the answer in the following link:
Node.js, Ajax sending and receiving Json
and I thought maybe i could use response.end and response.setHeader instead?
I'm not quite sure if my problem lies on the client side or the server side.
You don't
Listen to the right port (10901 vs 10351)
Send any parameters in the query section of the url
Need JSON.stringify because you already get a string in (req.query)
You should:
Make the ports match
Send parameters in the url ex:(url:'http://localhost:10351/function?foo=bar)
Remove the stringify ex:
res.send(req.query)
alert("ajax callaback response:"+data);
response.end is not needed if you already use the res.send method, and response.setHeader would be helpful if you want to mark this content as json, so you can put a Content-Type: application/json header,
Or use res.json to do both of these things for you (stringify the json and put the right header for you)
Your ports don't match in code. You said your call worked until console.log(), if the ports don't match it won't even enter app.get() in server.
I think you just posted a different code for client.
I will suggest you to try postman which is chrome extension that will be really helpful to send and get ajax request responses. Using you code just by changing the port number I am able to get the response in postman.

Categories

Resources