How to get data from $.post() request? - javascript

I'm trying to send post JQuery request, but I can't get them out in server written using Express.
Right now, I was trying to send data in this way:
Client side
$.post('http://localhost:8080/numberOfAnsweres',{'val': 2})
Server side
app.post('/numberOfAnsweres',(req,res,next)=>{
numberOfAnwers = req.??????
console.log(numberOfAnwers)
})
I don't know which parameter of req should I use.
I'm also not sure if the sending method is good, is there any better way?

You might get the values using express with:
app.post('/numberOfAnsweres',(req,res,next)=>{
var name = req.body.name,
var color = req.body.color;
var value = req.body.val;
})

Related

Unexpected "write after end" error in express

I am trying to proxy an api call from client side through my server for some third party service, reasons for this being CORS issues and adding in a secret key on the server side. I usually get it done in the following way:
app.use('/someService', (req, res) => {
let url = `https://example.com/${config.SECRET_KEY}/endpoint${req.url}`
req.pipe(request(url).pipe(res))
})
this way I can use any ajax library on the client side and perform get request for example: get: '/someService/params' and it would normally go through and perform that request and then pipe it back. However now I started getting:
Error: write after end
in express and I am not entirely sure about what could be causing it.
Your piping is wrong. As it is now, you're piping to res twice (.pipe() returns the argument passed to it for chainability).
Instead try this:
req.pipe(request(url)).pipe(res)
I should point out however that properly proxying the HTTP response is not quite that simple since currently this line will always respond with HTTP status code 200, no matter what the remote server for the middle request responds with. Also, any headers from that response will not be sent to res. With that in mind, you could naively try something like:
var proxiedRes = req.pipe(request(url));
proxiedRes.on('response', function(pres) {
res.writeHead(pres.statusCode, pres.headers);
// You will want to add a `pres` 'error' event handler too in case
// something goes wrong while reading the proxied response ...
pres.pipe(res);
});

request.body.email is undefined node js server side using http.get

I have a problem where request.body.email returns me undefined.
I wrote this code on my controller on my client side:
wish.controller('wishCtrl',['$scope','$http','$cookies',function($scope,$http,$cookies) {
var user={};
user.email = $cookies.get('cookieEmail');
console.log(user.email);
$http.get("http://localhost:3000/wishlist",user).success(function(data){
$scope.wishController = data;
console.log(data);
});
}]);
here I see - user.email ok so there is no problem here.
on my controller on my server side I wrote:
exports.getData = function(request, response) {
userEmail = request.body.email;
console.log(userEmail);
}
which writes me back undefined.
to call this function I have on my server.js (on the server side)
app.get('/wishlist',wish.getData);
any idea how to fix it?
You are making a GET request. There is no request body in a GET request.
If you want to read query string data then parse request.url.
The Angular documentation for get says that the last argument must be a configuration object. So it looks like you aren't even managing to put your data in the URL either. Pass a configuration too.
$http.get("http://localhost:3000/wishlist",user, {})
because i't get function have to pass the email on the client side this way:
$http.get("http://localhost:3000/wishlist/"+user.email)
and the path of the sever should recognize it that way:
app.get('/wishlist/:email',wish.getData);
and int the controller that way:
userEmail = request.params.email;
console.log(userEmail);

Use angular to call multiple actions from Node.js

Please help, I'm unflushed in programming  . I created a route router.get('/statistics', routesCtrl.statistics) for a page where I want to display some statistics in some charts, using Angular.
I realized that I need to send some query results like, how many registrations are in db, how many of them have "this property", how many of them have “those properties” and so on, being something new for me. Until now in responses of the routes I sent only one statistic from the above list.
How should I send this info to Angular, should I create a literal object containing those statistics, packing them in the response and send it to the Angular? Or to send the entire json from db and parse it in Angular, but it seems to be a wrong idea also because I can't use then mongoose queries from Angular if it's true :) .
I don’t have any other idea and there probably are more professional ways. Thank you!
It is very simple, whenever you need data from server side, which is node.js in your case or anything it may be like PHP, asp.nrt etc you have to send http requests to server using angular $http (GET/POST) and along with required parameters as a json object or query string. At server end write some rest service type stuff to handle this and make use of send parmeters at server to query mongo and than pass collected data as a json object back to angular end. At angular you can parse this JSON, and angular have also scope to use JSON/Array directly in view using attribute ng-repeat and so on depends on your exact requirement.
Request in angular.js
var sendConfig = {
method : "POST",
url: "YOUR_URL",
data: {action : 'Test_Service'},
headers : {}
};
$http(sendConfig).success(function(response) {
console.log(response);
}).error(function(error) {
console.log(error);
});
Response In node.js
var server = http.createServer(function(req,res){
var webservice_actions_instance = new webservice_actions(req, res);
var service_response = {data : 'RESPONSE_HERE_AFTER_CERTAIN_ALGOS'};
res.writeHead(200, {'Content-Type': 'text/html',"Access-Control-Allow-Origin": "*","Access-Control-Allow-Headers":" X-Requested-With"});
res.write('Response Data '+ service_response);
res.end();
}).listen( 8080 );

Nodejs and callbacks

I am very new to Node.js and how it's callbacks work exactly, I am trying to find some good documentation on it but it's just not clicking for me yet. I'm coming from python so I'll show an example of what I'm use to doing in python, I'm not sure if it's possible in node though
def getRequest(link):
url = urllib.request.urlopen(link).read().decode()
return url
class urlData:
def __init__(self, link):
self.results = getRequest(link)
I'm not sure if node can do this because it's async ways, or is it possible? I'm not sure how to go about this the correct way, how would I replicate this action in node? If not can the this code be toyed with to get similar results, a way to set the variable with the data that is going to come?
The way you might do this in node is the following:
Install Request. https://github.com/mikeal/request
var request = require('request');
Now we have a simple http client.
var data;
request.get({url:url, json:true}, function (e, r, body) {
// this will get called when the response returns. Your app will continue before this is called.
data = body; // i have no idea what you want to do with it
console.log(body); // should be json
})

Sending client side form input to server side database query via Node.js and return results to client

I am developing a web application where the user can type in a "device id" on the web page (we have 100's of devices out on the field in production use each with a unique ID), that result entered by the user will be sent to the Node.js server that in return will store it into a variable and use it in a SQL Query to retrieve results about that particular device from the database server and then display the results back to the client web page.
Currently the form input feature has not been implemented yet even though I've already coded the form code in html.
The program works fine as it is if I were to manually change the DEVICE_ID to the device I wish to retrieve data from in the code but of course I want to be able to enter this on the client page instead of me having to change it in the server-side source code manually.
"use strict";
var pg = require('pg').native;
var http = require('http');
var $ = require('cheerio');
var fs = require('fs');
var url = require('url');
var htmlString = fs.readFileSync('index.html').toString();
var parsedHTML = $.load(htmlString);
var dbUrl = "tcp://URL HERE/";
// The Sign-ID
var DEVICE_ID = '2001202';
// Create the http server
http.createServer(function (request, response) {
var request = url.parse(request.url, true);
var action = request.pathname;
// Connect and query the database
pg.connect(dbUrl, function(err, client) {
// The complete sql query for everything that's needed for the app!
client.query("SQL QUERY IS HERE" + DEVICE_ID + "etc..",
function (err, result) {
// Remaining program code is here that performs DOM based
// manipulation to display results returned from the server
// to the client side page.
// Time to Render the document and output to the console
console.log(parsedHTML.html());
// Render the document and project onto browser
response.end(parsedHTML.html());
}
); // End client.query
}); // End pg.connect
}).listen(8080); // End http.CreateServer
pg.end();
I've considered the following:
1) Use An OnClick() function from within the HTML code, like this:
onclick="lookupSignID()
Then include an external JS file from within the HTML that includes the lookupSignID() function however I soon found out this is only performing client-side function and is not what I want.
2) AJAX is only good for if the server is generating new information by itself, therefore I can't use AJAX since the user is entering the device ID to get information from it.
3) Possibly using POST/ GET
Can anyone please advise on what course of action I should take? If solution (3) is the best way how would I go about doing this? Can it be integrated into my existed code (shown above) without many changes?
Thanks!
If you used jQuery on the client side with an AJAX POST function, and then on the server side, you have express.js, you could do this:
app.post('/deviceid', function(req, res) {
var deviceid = req.param('deviceid')
console.log(deviceid)
...
})

Categories

Resources