How to read the data from node js post ajax request? - javascript

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

Use this npm package - https://www.npmjs.com/package/body-parser
and so server site parse like this:
request.body.{some field name}

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.

Related

req.body.item undefined - DELETE request express js

I am a beginner to web development, and I am having trouble retrieving the parameters when sending a delete request to my local REST API (written using Express Js). I have already Googled the issue, but most are resolved by using body-parser.
When I return and print the req.body back to the console it comes out as:
{data: "{"Customer":"1"}"}
which seems to look correct?
But when I try and retreive
req.body.Customer;
in the routes.js file it comes out as undefined.
Am I missing something really obvious here?
JQuery function to make request
function DeleteItem(){
let data = {
Customer: $customerId.text()
}
data = JSON.stringify(data);
$.ajax({
url: "http://localhost:3000/Customers",
type: 'DELETE',
data: {
data
},
success: function(res) {
console.log(res);
BuildTable();
},
error: function(res) {
console.log(res);
alert(res);
}
});
}
Routes.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var appRouter = function(app) {
app.delete("/Customers", function(req, res) {
var customer = req.body.Customer;
console.log(customer);
res.send(req.body);
});
}
module.exports = appRouter;
First delete the line data = JSON.stringify(data);
then if you need the Customer you should write:
req.body.data.Customer;
or you can change your request like this:
function DeleteItem(){
let data = {
Customer: $customerId.text()
}
$.ajax({
url: "http://localhost:3000/Customers",
type: 'DELETE',
data: data,
success: function(res) {
console.log(res);
BuildTable();
},
error: function(res) {
console.log(res);
alert(res);
}
});
}
Right now you are creating a new object data and assigning the object you created before to it.

getting response from post request

I'm trying to do simple login modal using POST jQuery AJAX,
but I'm not getting any response from the server
client:
$(document).ready(function(){
$("#loginReq").click(function(){
$.post("/login",
{
uname: document.getElementById("username").value,
psw: document.getElementById("password").value
},
function(data, status, jqXHR) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
server:
app.post('/login', function (req, res) {
var username = req.body.uname;
var password = req.body.psw;
var i;
for (i=0; i < users.length; i++)
if (username == users[i].username && password == users[i].password)
{
console.log('found');
//res.send('OK');
//res.sendStatus(200);
res.status(200).send('OK');
break;
}
if (i == users.length)
{
console.log('not found');
res.sendStatus(300);
}
console.log('end of listener');
});
I've tried res.sent, res.end, res.statusCode, res.status.send,
but whatever I tried the alert on the client side won't pop.
(my goal is to get an empty response - only status code, no body,
but nothing works)
Here is a simple example that should help you I think.
First npm install body-parser
On your server use the body-parser middleware:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/login', (req, res)=> {
res.send(JSON.stringify(req.body));
});
In your jQuery file prevent the form from submitting - note here loginReq is an id on the form itself:
$(document).ready(function(){
$('#loginReq').submit(function(e) {
e.preventDefault();
$.ajax({
url: '/login',
type: 'POST',
cache: false,
data: {"username": document.getElementById("username").value},
success: function(data){
alert(data);
}
, error: function(jqXHR, textStatus, err){
alert('error ' + err);
}
});
});
});
This will pop up an alert with your data.
You've defined a server on the backend, but you haven't started it up. Check out the example code on the express website here to see how to start up your server.
TL;DR - try adding the following to the bottom of the server file:
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})

when i use ajax post json to web server(Nodejs), but the web server can't receive the data from client

the client code :
self.getjson = function () {
var timeinfo = new Object();
timeinfo.time = self.time;
timeinfo.address = self.address;
timeinfo.info = self.info;
return JSON.stringify(timeinfo);
};
alert(self.getjson());
$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url:'/user/add/timetemp',
data: self.getjson(),
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
}
})
the server code app.js:
router.route('/user/add/timetemp')
.post(function(req,res){
console.log(req.body); // your JSON
res.send(req.body); // echo the result back
});
the answer from client:
enter image description here
there has data in the client.
the answer from server:
but the server is null
From the documentation:
req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
(My emphasis.) It continues with:
The following example shows how to use body-parsing middleware to populate req.body.
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
Side notes:
1. All of these variables on self are global variables. Global variables are a Bad Thing™. :-) Generally best to put your code in a scoping function and use locals within that scoping function.
2. new Object is almost never needed. Your getjson function can be much simpler:
self.getjson = function () {
return JSON.stringify({
time: self.time,
address: self.address,
info: self.info
});
};
or (slightly more convenient when debugging):
self.getjson = function () {
var timeinfo = {
time: self.time,
address: self.address,
info: self.info
};
return JSON.stringify(timeinfo);
};
3. There's no need for your beforeSend callback on ajax; just use the built-in contentType option:
$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url: '/user/add/timetemp',
data: self.getjson(),
contentType: 'application/json',
success: function(data) {
}
});

how to read my json and send it to an email in pure nodejs

I would like NodeJS server, post.js file, to send the json object from the AJAX request to an email using only pure NodeJS.
The following is the front-end code that sends the AJAX request:
$(document).ready(function() {
$("#contact").submit(function () {
var data = {};
$.each($(this).serializeArray(), function (key, value) {
data[value.name] = value.value;
});
data.interest = [data.interest1, data.interest2, data.interest3];
delete data.interest1;
delete data.interest2;
delete data.interest3;
console.log(data);
$.ajax({
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
url: "post.js",
success: function (data) {
$("#contact").addClass('success');
},
error: function () {
$("#contact").addClass('error');
}
});
return false;
});
});
Nodemailer offers a great way to have your node.js server send emails with easy setup. With this you can set up a simple node server such as:
//untested node.js code only for reference.
var express = require('express')
var app = express();
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var transporter = nodemailer.createTransport('TODO: setup your SMTP');
app.post('/', function (req, res) {
var mailOptions = {
from: "TODO: sender",
to: "TODO: recipient",
text: req.body
}
app.listen('TODO: some port');
Check nodemailer's documentation for details on setting up the server to suit your needs.

Get "syntax error Cannot GET /xyz" with jQuery AJAX

I use $.ajax to request data from a node.js server. I'm debuging the client side in Firefox. I get the following error in the console: Syntax error Cannot GET /xyz where /xyz is the route for my server. However, the page works properly. I would like to avoid filling the console with this error because the AJAX request is done recursively.
Client code:
startUpdateGui = function(){
(function updateGui(){
$.ajax(
{
url: "/updategui",
type: "POST",
data: {
id: "master"
},
timeout: 10000,
}
).done( function( data ){
$( "#time_server" ).text( data );
updateGui();
});
})();
}
startUpdateGui() is called once at the end of <body>. Notice again that the function performs what I want it to do. done() is correctly executed.
Server code:
app.post( '/updategui', function( req, res ){
//log.mark( 'Routing \'/updategui\' with id = "' + req.body.id + '"' );
res.end( (new Date()).toString() );
});
where app is from Express.
So, looking at the client $.ajax(...) and the server app.post(...) can you see where the problem is?
Thanks for your help!
What version of jquery are you using? Is it prior to 1.9.0?
http://api.jquery.com/jquery.ajax/. Basically if you don't set it, it's defaulted to be get.
Anyway can you update that to method? Also you call the updateGui() inside updateGui().
I'm not sure if you want it
(function updateGui(){
$.ajax(
{
url: "/updategui",
method: "POST", // <---- updated
data: {
id: "master"
},
timeout: 10000,
}
).done( function( data ){
$( "#time_server" ).text( data );
updateGui(); // <--- recursion
});
})();
This is my Nodejs code.
var express = require('express');
var app = express()
.all('/updategui' , function(req, res, next){
// res.write('all\n');
next();
})
// app.get('/', function(req, res, next){
// res.end('get\n');
// })
.post('/updategui', function(req, res, next){
res.end('post\n');
})
app.listen(3000);

Categories

Resources