Baner Baner - 1 year ago 82
Node.js Question

Can you send data to post method of node js using AJAX/jQuery'/output2', function(req, res){
//Send UDP packet continuously every ten seconds
var HOST= '';
var PORT= 69;
var number= req.body.number;
//Reading in the user's command, converting to hex
var message = new Buffer(number, 'hex');

//Sends packets to UDP

client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;

client.once('message', function (message) {
var val = message.toString();
res.render('index', {val:val});


$(function() {
$('#loadRequest').click(function() {
$.post('/output2',function(res) {

I have a udp server that sends back different message each time a message is sent to it. If i hard code the a message into the var message, then everything works. But i want the client to able to manually type in a message, then when the refresh button is pressed, the ajax re sends that same inputted message again. Right now, nothing happens when the button is pressed because ajax doesn't know what req.body.number is.

Answer Source

You can use jQuery's $.post() method to send a json object, or you can url encode parameters:


$.post('/output2', {parameter1: 'value1', parameter2: 'value2'}, function(data){
    // Do things


$.post('/output2?parameter1=value1&parameter2=value2', function(data){
    // Do things

To receive these parameters on your post route you can use the req.params variable:'/output2', function(req, res){
    var param1 = req.params.parameter1;
    var param2 = req.params.parameter2;
    // Do things