Pass Parameter From client side Node js - javascript

I am having a basic doubt here, which i can't make it. I have to pass two variables to server side .What i did was
Client Side
$("#send").click(function () {
var getUsrName = $("#text").val();
var getPass = $("#pass").val();
$.post('/connect', {
usr: getUsrName,
pass: getPass
});
});
Server Side
app.post('/connect', function (req, res) {
console.log("req.body : ",req.body.usr)
});
Instead of request.body, I used req.params and req.query. But none of them are working. Its showing undefined.
Thanks

What you're sending to the server is the payload. Just try to console log the whole request coming from the client console.log(req)
from there you will see what you have and again try to console.log(req.payload)
Thanks.

Related

Handling ajax requests, not receiving data

i'm having a hard time setting up my client-side ajax calls to send data to node express server.
i want to fire my ajax request "onclick" of an href link.
I'm trying to send the ID of the link as a variable to the server, but the server doesn't receive my data (without setInterval)
if i put the ajax request inside a setInterval() (which i don't want to do, because i only want to send the data once a link is clicked to the server),
the server receives the data in res.req.body, why?
client side:
$('.link_group').click(function () {
data = $(this).attr('id');
$.ajax({
type: "POST",
url: "/ajax_handler",
data: {id: data}
});
});
server side
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(res.req.body) {
console.log(res.req.body);
}
});
Is this even a common way to "catch" the data from client?
if(res.req.body) {...
doesn't seems right, but i don't know how to do it in a smarter way / can't find any good examples.
I'm about to fire 3-4 Ajax other requests to /ajax_handler which leads to my next question: how to handle multiple ajax requests to the same url?
Thanks in advance!
Are you parsing the request? req.body is initially empty/undefined. You will need to pass it to a middleware that parses the data into req.body. Body-parser is a nodejs module that can achieve this. Here's how to a POST request with JSON data being sent.
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(req.body) {
console.log(req.body);
}
});

Neither Node.js PUT or POST routes are presenting the data that is being received

I tried this with a number of different modules and methods.
Even by proving the other modules do work as expected in Node by building a separate test project and testing each module individually.
Posting FROM Node's hosted router to a remote API (not TO Node's hosted API)
This problem is not one of SENDING data to an API. It must IMO a problem in the receiving API's not giving up the data it IS receiving for some reason.
I've proven the PUT or POST calls are sending the data by sending the call to http://httpbin/org. That site shows me I'm sending what I expect to be sending.
Here is how I'm sending. I can even see in the receiving API that that API is certainly getting called successfully.
-- sending -- ((Again. This shows my node.http attempt. But I get the same problem using requestjs, requestifyjs, needlejs))
router.get('/', function (req, res, next) {
var hst = req.headers.host.split(':');
var lookbackURL = 'https://' + req.headers.host + req.baseUrl;
lookbackURL = 'http"httpbin.org/put';
var dat = {
what: 'ever'
, try: 'again'
};
var bdy = JSON.stringify(dat);
var options = {
host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'
, headers: { 'Content-Type': 'application/json' }
};
var r = nodeHttp.request(options); r.write(bdy); r.end();
res.sendStatus(200);
});
-- receiving --
router.put('/', function (req, res, next) {
console.log('r', req);
});
No matter what module or method I use, in all cases, the receiving req object doesn't contain the what or try data.
BUT in my test project the data is there as I expect it to be, in all cases.
Doing the same console.log(req); in the test project, reqestjs, requestjs, needlejs, node.http all show a proper body object.
But in this problem there isn't a body object in req.
And sending this put/post to http://httpbin.org I can see the body object is being sent.
Any ideas?
Issue found. And it was something no one on here could have gotten for the code I posted.
For reasons I will not go into I have to take body-parser out this application. This also means app.use() won't have a parser given to it.
And that means I have to deal with getting the data on my own. So I've added a req.on('data') listener to read the chunk from the call to the API.
router.put('/', function (req, res, next) {
var data = '';
req.on('data', function (chunk) {
data += chunk;
.....
});
.....
I also decided to do this as a PUT using Requestify.
This just goes to show how easy it is to become complacent and forget how things really work; the assumption of body-parser (or other things) always being there for instance. Or what it is really doing for you.
NEXT I have to figure out how to get a value out of the `req.on('data) back to the method PUTting to the API. Any tips? Appreciated.

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);

any way to send a function with socket.io?

guys.
I want to send a function to browser with socket.io, but failed to do it.
On server side, I response a function with emit, but I get a undefined on browser.
Is there any way to get a function from server with socketio?
there is my code.
// server.js
var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function(req, res) {
file.serve(req, res);
}).listen(8000);
io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('schedule', function() {
console.log('SCHEDULE TASK');
socket.emit('schedule', function() { console.log('hello world'); });
});
});
// client.js
var socket = io.connect('http://localhost:8000');
socket.on('schedule', function(fn) {
fn();
});
socket.emit('schedule');
You cannot send an actual function. You could send a string of Javascript and then you could turn that into a function in the client.
But, I'd suggest you really ought to rethink what you're trying to do here. Generally, the client already has the code it needs (from the script tags that it downloaded) and you send the client data which it then passes to the code it already has or data that it uses to make decisions about which code that it already has to call.
If you show us the real world problem you're trying to solve, we can likely suggest a much better solution than sending a string of Javascript code to the client.
If you really wanted to send a function, you would have to turn it into a string first, send the string, then use the string to turn it back into a function in the client by using a Function object or eval() or creating your own dynamic script tag with inline source.
You can only send strings via socket.io, not functions. That being said, I suggest you to send function names instead.
//server.js
socket.emit('schedule', 'helloworld');
//client.js
function helloworld(){
console.log('hello world');
}
socket.on('schedule',function(name){
window[name](); //hello world
});

JSONP call with server-side language as Javascript

I've been trying to use JSONP to get a JSON object from a server via a client-side call (on a different port). However, because my server is implemented in javascript using Node.js and Express, I haven't been able to find much on JSONP with Javascript on the server as most sites I found used php for server-side code.
I believe the issue is with how I set up the url with respect to the callback, which I'm a bit fuzzy on cause it's new to me.
On the server:
//Setting up server stuff
var express = require('express'),
app = express.createServer();
app.use(express.logger());
//Making a connection to the mongoDB to get the data that I want to display in the JSON object
new Db('prism',
new Server("127.0.0.1", 27017, {auto_reconnect: false}), {}).open(function(err, db) {
app.get('/getData', function(req, res) {
console.log('JSONPCALLBACK CALLED WITH RETURNDATA PASSED IN; SERVER SIDE');
if (typeof callback == 'function') {
console.log('callback is defined');
callback(returnData);
}
else {
console.log('callback is not defined');
}
}
});
And on the client:
$.ajaxSetup({ cache : false });
$.getJSON('http://127.0.0.1:1337/getData&callback=?', function(rtndata) {
console.log('SUCCESS');
console.log(rtndata);
});
embedded by the standard tags.
But I get the error:
GET http://127.0.0.1:1337/getData&callback=jQuery16108897686484269798_1311007334273?_=1311007334342 404 (Not Found)
The server is on port 1337 while the client is run through MAMP on localhost:8888. I'm not sure if its even a localhost related issue as I've been trying to get this setup running for a few days now.
I believe the issue has something to do with not writing this line, which is in php, into my server-side Javascript. Most of the JSONP examples I found had something like this. But I'm not sure.
if ($GET['callback'] != '')
$json = $GET['callback']."( $json )";
return $json;
Any help would be greatly appreciated. I apologize ahead of times for being super verbose.
Bests,
Cong
I think you have two problems. First is the 404. Completely separate from getting the client-side jQuery code to work, you need to make sure that you can issue a regular browser request (i.e. paste in that URL) and get back what you expect. I haven't used express, so it's hard for me to comment on why you'd be getting that, except to say that I don't see 1337 anywhere in your server-side code, just what appears to be the port number 27017.
The second problem is that you don't actually want to execute the callback on the server, just build the JSON response including the callback (string) prefixed to it.
So instead of this ...
if (typeof callback == 'function') {
console.log('callback is defined');
callback(returnData);
}
else {
console.log('callback is not defined');
}
try this:
if (callback) {
console.log('callback is defined');
res.write(callback + '(' + JSON.stringify(returnData) + ')');
}
else {
console.log('callback is not defined');
}
Hope this helps!
From http://api.jquery.com/jQuery.getJSON/ there is an example that includes 2 '?' in the URL.
you only have one, so try
$.getJSON('http://127.0.0.1:1337/getData?callback=?', function(rtndata) {
and see if that gets rid of your 404
then look #jimbojw suggestion for returning a proper jsonp formated responce.
Use this:
var express = require("express");
var server = express.createServer();
server.enable("jsonp callback");
server.get("/foo", function(req, res) {
// this is important - you must use Response.json()
res.json("hello");
});
jsonp with node.js express

Categories

Resources