getting response from post request - javascript

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!')
})

Related

Why is data not received by Node.js through POST request?

So I have this functionality.
The client is sending data through jquery post function
$.post(currentURL + "/api/tables", newReservation,
function(data) {
if (data == true) {
alert("Yay! You are officially booked!")
}
if (data == false) {
alert("Sorry you are on the waitlist")
}
$('#reserve_name').val("");
$('#reserve_phone').val("");
$('#reserve_email').val("");
$('#reserve_uniqueID').val("");
});
Then Node.js is receiving it here
app.post("reserve/api/tables", function(req, res) {
var newentry = req.body;
console.log(newentry);
entries.push(newentry);
res.json(newentry);
});
However, console.log is giving me this error
jquery.js:9631 POST http://localhost:8080/api/tables 404 (Not Found)
Because you are doing the request to the url: http://localhost:8080/api/tables , but your server is waiting you at : "reserve/api/tables".
Try to target: http://localhost:8080/reserve/api/tables
your routing specifies a localhost:8080/reserve/api/tables,
remove the 'reserve' routing
You are missing leading slash in
app.post("reserve/api/tables", function(req, res) {
so it should be
app.post("/reserve/api/tables", function(req, res) {
or
app.post("/api/tables", function(req, res) {
as edited later

how to upload file on server in node js?

could you please tell me how to upload the file on some directory current example (uploads folder) .Here is my server side code
app.post('/upload', function (req, res) {
console.log('abcc')
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
res.json({error_code: 0, err_desc: null});
});
});
full code node js
https://repl.it/repls/LustrousCharmingCommunication
I used this server and hit the service using client and upload only attached file
here is my request client code
https://jsbin.com/luwezirive/edit?html,js,output
$(function () {
$('.submit').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
if ($('#fileId').val().length === 0) {
alert('please insert file')
} else {
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
console.log('fffff')
$.ajax({
url: 'https://lustrouscharmingcommunication--five-nine.repl.co/upload',
type: 'POST',
data: data,
cache: false,
enctype: 'multipart/form-data',
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR) {
console.log('succsss');
if (typeof data.error === 'undefined') {
// Success so call function to process the form
}
else {
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
})
})
I am getting success but file is not uploaded why ?
upload method
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
any update ?
The simplest way is using multer. https://github.com/expressjs/multer
Example taken from the documentation:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})

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

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.

Express POST - Returned JSON is treated as invalid by JQuery

I am trying to write a small authentication service using Express and Node.
I did a search on SO and don't seem to find my answer
even though there're many similar questions but no
definitive answer really.
I tried many variations of my server side code but
seems I am still missing something.
The POST call is made from an HTML page
with some JQuery code (ajax call).
I enter the post() method in Express but when
it returns response to the HTML page, always the ajax
error handler is executed, never the success handler.
My JSON which I return seems valid to me.
I tried calling send and json on the
response object but nothing really works.
What am I missing?
Any help would be greatly appreciated.
Thanks in advance.
var mod = require('express');
var auth = require('./login_module.js'); // my module
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/login', function(request, response) {
console.log("post method called");
var credentials = request.body;
console.log("credentials = " + credentials);
console.log(credentials);
auth.authenticate(credentials.username, credentials.password, function(result){
console.log("Authentication Result: " + result);
var code = result === 1 ? 200 : 401;
console.log("Response Code: " + code);
var res = {
data : "Response Code: " + code
};
console.log(JSON.stringify(res));
// So far I am good!
response.statusCode = code;
response.json(res);
// Response is now sent
// but not recognized as
// valid JSON in the client.
console.log("response sent");
});
});
app.listen(10101);
JQuery call.
<script type="text/javascript">
$(document).ready(function(){
$( "#btn" ).click(function(){
alert('calling now!');
var obj = {
username: $('#usrn').val(),
password: $('#pwd').val()
};
$.ajax({
type: "POST",
url: 'http://localhost:10101/login',
data: obj,
success: function (data, textStatus, jqXHR){
alert('got response back!');
if ("200" === textStatus){
$('#status').text('Login succeeded!');
}else if ("401" === textStatus){
$('#status').text('Login failed!');
}else{
$('#status').text('Invalid status received: ' + textStatus);
}
},
error : function(jqXHR, textStatus, errorThrown){
alert("Error when getting response.");
},
dataType: 'json'
});
})
});
</script>
As adeneo pointed out the key was to serve the html page over
http and not over file protocol. The rest was just some tuning
of various details about the Ajax jQuery call.
Server-side code:
var mod = require('express');
var auth = require('./acct_module.js');
var fs = require('fs');
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/login', function(request, response) {
console.log("POST called - try to login against the MongoDB.");
var credentials = request.body;
console.log("credentials = " + credentials);
console.log(credentials.username);
console.log(credentials.password);
auth.authenticate(credentials.username, credentials.password, function(result){
console.log("Authentication Result: " + result);
var code = result === 1 ? 200 : 401;
var message = result === 1 ? "Login succeeded!" : "Login failed!";
console.log("Response Code: " + code);
var res = {
message: message,
code : code
};
console.log(JSON.stringify(res));
response.statusCode = code;
response.json(res);
console.log("POST response sent.");
});
});
app.get('/login', function(request, response){
console.log("GET called - send back the HTML file.");
fs.readFile('login.html', function (err, data) {
if (err) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write("Request failed.");
response.end();
return;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
console.log("GET response sent.");
});
});
app.listen(10101);
Login page login.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( "#btn" ).click(function(){
// alert('Now calling the auth manager!');
var obj = {
username: $('#usrn').val(),
password: $('#pwd').val()
};
$.ajax({
type: "POST",
url: 'http://localhost:10101/login',
data: obj,
success: function (data, textStatus, jqXHR){
// alert('success called!');
var res = JSON.parse(jqXHR.responseText);
$('#status_message').html(res.message);
$('#status_code').html(res.code);
},
error : function(jqXHR, textStatus, errorThrown){
// alert('error called!');
var res = JSON.parse(jqXHR.responseText);
$('#status_message').html(res.message);
$('#status_code').html(res.code);
},
dataType: 'json'
});
})
});
</script>
</head>
<body>
<input type="text" id="usrn" name="usrn"/><br>
<input type="password" id="pwd" name="pwd"/><br>
<input type="button" id="btn" name="btn" value="LOGIN!"/><br><br>
<div id="status_message" name="status_message"></div><br>
<div id="status_code" name="status_code"></div><br>
</body>
</html>
This does what you're looking for: https://github.com/braitsch/node-login
I'd recommend grabbing that from git and looking through it. You could even use it as a template. Pretty good stuff, and when you want to see the client side of things you can just look at the scripts associated with the login page.
example here:
http://node-login.braitsch.io/

HTTP GET inside a api method called by the client

Hi I have a rest api set up in Nodejs and the ajax call is working perfectly, that is until I try to call an external REST service from within the method.
Can anyone help me out to work out why this wont work? I'm using Nodejs with Express running on port 3000, basically localhost at the minute. Bellows my work in progress but its been changed alot. I was using the request module but now have went back to http.
app.get('/api/exchange', function (req, res){
var text = '';
var options = {
host : 'rate-exchange.appspot.com',
port : 3000,
path : '/currency?from=GBP&to=USD',
method : 'GET'
};
var call = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
text = "made it in";
res.on('data', function(d) {
text = "here";
});
});
call.end();
call.on('error', function(e) {
text = "error";
});
res.json({ msg: text });
});
Excuse my classic javascript debuging technique, I'm basically just using text to see where its going.
When I run this I get the following back.
{
"msg": ""
}
p.s. anyone knows of any good debuging tools for node I'd be greatful.
I guess port:3000 is wrong. And you should get response from http.request callback function.
app.get('/', function (req, res){
var text = '';
var options = {
host : 'rate-exchange.appspot.com',
//port : 3000,
path : '/currency?from=GBP&to=USD',
method : 'GET'
};
var call = http.request(options, function(resp) {
console.log("statusCode: ", res.statusCode);
text = "made it in";
resp.on('data', function(d) {
text = "here";
console.log("response data: "+d);
});
});
call.end();
call.on('error', function(e) {
text = "error";
});
//res.json({ msg: text });
});

Categories

Resources