Reputation: 145
I am trying to send a data from client to server (node js) . I am using ajax .
client :
$("#test_button").on("click",function(){
//alert("shit");
$.ajax(
{url: "http://localhost:4000/ajax_check",
async: false,
type: "POST",
data: "{user:balayya,password:hero}",
success: function(result){
alert("hooli");
}});
});
server:
var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
http.listen(process.env.PORT || 4000, function() {
console.log('listening on *:4000');
});
app.use(express.static('publuc'));
app.get('/', function(req, res) {
console.log("new entry page serving");
res.sendFile(__dirname + '/main.html');
});
app.post('/ajax_check', function(req, res){
console.log("someone came in here");
console.log(req.query.data);
});
the console.log() is printing as "undefined" . What is the correct way to receive a post request and it's data from the client in node js
Upvotes: 1
Views: 6437
Reputation: 26
Use this npm package - https://www.npmjs.com/package/body-parser
and so server site parse like this: request.body.{some field name}
Upvotes: 1
Reputation: 1039408
Try like this:
$.ajax({
url: "http://localhost:4000/ajax_check",
type: "POST",
data: {
user: "balayya",
password: "hero"
},
success: function(result) {
alert("hooli");
}
});
And on the server use req.body.param_name
to read the corresponding parameter value:
app.post('/ajax_check', function(req, res){
console.log("someone came in here");
console.log(req.body.user);
console.log(req.body.password);
});
Also notice that I have removed async: false
from your AJAX request because every time someone sets this property to false
a poor kitten dies.
Upvotes: 0