Nodejs page freezes after multple requests to Custom API - json

The problem I have is that my application works when I submit only one 1 when I press the Submit button multiple times it freezes and after some time (about 1000.000 ms) it returns the last request in the console and jade page. The submit button returns a post from the form and sends it to the same page . What the button also does is Refreshing the page. It is important that the page returns the (JSON) post to the page and there is an other json request that sends it to the API(and returns it to the same page )
app.js
var options_search = {
hostname: 'host',
path: 'path',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': JSON request .length,
}
};
app.post('/result',function(req,response){
var keyword=req.body.user;
GLOBAL.objToJson ={ keyword };
response.write(JSON.stringify(GLOBAL.objToJson));
console.log("test " +JSON.stringify(GLOBAL.objToJson) );
});
app.get('/Search', function(req, res) {
var req = http.request(options_search, (resb) => {
var buffer_search = "";
resb.setEncoding('utf8');
resb.on('data', (chunks) => {
buffer_search += chunks;
});
resb.on('end', () => {
res.render('Search',{
title: 'Search',
value_search: buffer_search,
search_test: [JSON.stringify(GLOBAL.objToJson) ]
});
});
});
//res.redirect("/search");
req.write(search);
});
search.jade
doctype html
html
head
script(src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js')
script.
$(document).ready(function(){
var user,pass;
$("#submit").click(function(){
user=$("#user").val();
pass=$("#password").val();
$.post("http://localhost:3000/result",{user: user}, function(data){
if(data==='done')
{
alert("login success");
}
});
});
});
input#user(type='TEXT', size='40')
br
input#submit(type='button', value='Submit',onclick="location.href='search'")

In the result route you are using the underlying HTTP .write() method to respond to the client. However this does not end the connection, which will stay open expecting more things to be written to the client.
If you are sending a string you should use .send() as that will write the string to the HTTP stream and end the response.
You may also want to consider not stringifying the object to a JSON string and just using .json() instead. So the line of code
response.write(JSON.stringify(GLOBAL.objToJson));
becomes
response.json(GLOBAL.objToJson);

Related

send post from webpage to Node.js server ...do not use 'fetch'...?

I am using the following javascript on a webpage to send information to a Node.js server upon a "click" on an image. This is using a 'POST' request.
<script>
function rerouter(_sent) {
var _people = <%- JSON.stringify(member_list) %>;
//convert the passed ('member_list') array into a JSON string...
var _attend = <%- JSON.stringify(online) %>;
//convert the passed ('online') array into a JSON string...
var splits = _sent.id.split("_"); //"split" on "underscore ('_')"
if (_people.indexOf(splits[1]) != -1) {
//**SEND INFO TO SERVER...
var available = _attend[_people.indexOf(splits[1])];
var response = fetch("members/pages/:" + splits[1] + "/presence/:" + available, {
method: 'POST',
headers: {
'Content-Type': 'text/plain;charset=utf-8'
}
});
//**
} //'_people' array contains the member name ('splits[1]')...
}
</script>
And here I handle the request in my Node.js server code:
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/members/pages/:membername/presence/:online', urlencodedParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:")
console.log(req.params)
console.log(req.body)
res.redirect('/_landing');
})
Here is my console output:
I RECEIVED FROM CLIENT THE FOLLOWING:
{ membername: ':Nica', online: ':Yes' }
{}
As can be seen from my output, the POST route does seem to be functional, somewhat. However my 'redirect' command does NOT execute...the webpage does not change to the '_landing' page as it should...I think it may be because I am using 'fetch' to send the POST request...??? Can somebody verify if that is the cause (or another issue is the cause) and how I might be able to correct the issue?
In addition why does my 'params' include the colons (":") when I log to the console...is that standard? I would not think it would include the colons in the log, only the actual data.
Basically it seems my POST is almost working...but not exactly. Any suggestions would be greatly appreciated. I thank you in advance.
UPDATE: I have made some changes and my POST seems to be working fine now. In my frontend webpage I use the following to make the HTTP POST request:
<script>
function rerouter(_sent) {
var _people = <%- JSON.stringify(member_list) %>;
//convert the passed ('member_list') array into a JSON string...
var _attend = <%- JSON.stringify(online) %>;
//convert the passed ('online') array into a JSON string...
var splits = _sent.id.split("_"); //"split" on "underscore ('_')"
if (_people.indexOf(splits[1]) != -1) {
//**SEND INFO TO SERVER...
var available = _attend[_people.indexOf(splits[1])];
fetch('/members/pages/callup', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({name: splits[1], presence: available, str: 'Some string: &=&'})
})
//**
} //'_people' array contains the member name ('splits[1]')...
}
</script>
...And modified my route handler in my Node.js script:
// create application/json parser
var jsonParser = bodyParser.json()
app.post('/members/pages/callup', jsonParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:")
console.log(req.body)
res.redirect('/_landing');
})
This is functional...to receive the data sent from the frontend webpage.
The only remaining problem is why does the 'redirect' not fire...??? I still have a feeling that by using a 'fetch' that somehow this is interfering with the page redirection...? A fetch would normally be used to wait for a response from the server, in my case I am not interested in that functionality I just want to send data one-way from frontend to backend...and then redirect the frontend page. I cannot think of any other reason why the redirect does not fire...?
Make extented:true instead of false as,
var urlencodedParser = bodyParser.urlencoded({ extended: true }) and move this line above of the below statement,
var jsonParser = bodyParser.json() and check if it works.
And finally change your headers here from,
headers: {
'Content-Type': 'text/plain;charset=utf-8'
}
To,
headers: {
'Content-Type': 'application/json'
}
Hope this will resolve the issue.

AJAX HTTP-POST-Request - Saving JSON responses

I want to make a HTTP-POST-Request with AJAX to call a JSON API. So, the API should return a response in JSON. I can see on the console of the API, that the request is successful. But the problem is, that no data or status is returned, or that I can't use it with JQuery. Here is my function:
$.post("http://api-adress/controller",
{
email: input_mail,
password: input_pw
},
function(data, status){
alert(data);
alert(status);
}, 'json');
I guess the problem is that the response from the Server does not get saved in the variables data and status correctly.
I would suggest to change a little bit your code like below:
var dataString = {
email: input_mail,
password: input_pw
}
$.post("http://api-adress/controller", dataString, function (result) {
})
.done(function (result) {
//Here is your result. You must parseJSON if it is json format
var data = jQuery.parseJSON(result);
})
.fail(function () {
//use this if you need it
})
Also make sure that you get the response through firebug in console tab. You can check there what you post, what you get etc.

AngularJS File Upload to Backend Express Server

I am trying to do a file upload using angularjs, using angular-file-upload library (https://github.com/danialfarid/angular-file-upload)
Here is my code
// ===============================My HTML File===========================
<input type="file" ng-file-select="onFileSelect($files)">
// ===============================My Controller==========================
var $scope.formObj = {
name: "Test"
};
var fileToUpload;
$scope.onFileSelect = function (file) {
fileToUpload = file[0];
};
// POSt request to /api/items
$scope.addItem = function() {
console.log($scope.formObj);
$scope.upload = $upload.upload({
url: '/api/items',
method: 'POST',
data: { myObj: $scope.formObj },
file: fileToUpload
}).success(function(data, status, headers, config) {
console.log("success");
});
};
// ================================My Backend=============================
// This is the function that will receive POST request to /api/items
exports.create = function(req, res) {
console.log(req.body); // req.body is just an empty object. ==> {}
// apparently, I found all the data to be in req._readableState.buffer[0]
// in the form of a buffer
var buffer = req._readableState.buffer[0];
// trying to console.log the buffer.toString, resulting in something similar to this
// { name: "Test", image: Object }
console.log(buffer.toString());
return res.send(200);
};
So my backend received the formObj with all its properties and values, however, the actual file data itself, whether in the form of buffer, or base64, or whatever, never gets received.
I wonder why. This is my first time working with file uploading, so I don't understand the concept.
Please point me in the right direction
If you are using Latest version of Express, you'd notice that
app.use(express.multipart()); is no longer bundled with express.
So do the following configuration changes. in express.js
var multer = require('multer');
app.use(multer({ dest: './uploads/'}));
You'd find that after doing this you would find the data and file , in req.body req.file respectively.
Hope it helps

Node Express 4 get header in middleware missing

I have a middleware function using Node's Express4 to log each request & response for debugging. I use the res.json call in the request handler to send back JSON to the client for all but static files. So I do not want to log the response for static files, but only the JSON responses. I have the following code:
function logRequests(req, res, next) {
// do logging (will show user name before authentication)
logger.reqLog('IN '+req.method+' '+req.url, req);
var oldEnd = res.end,
oldWrite = res.write,
chunks = [];
res.write = function(chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function(chunk, encoding) {
if(chunk) {
chunks.push(chunk);
}
oldEnd.apply(res, arguments);
// the content-type prints "undefined" in some cases
// even though the browser shows it returned as "application/json"
console.log('type='+res.get('content-type'));
if(res.get('content-type') === 'application/json') {
var body = Buffer.concat(chunks).toString('utf8');
logger.info(body, req);
}
logger.reqLog('OUT '+req.method+' '+req.path, req);
};
next(); // make sure we go to the next routes and don't stop here
}
So why do some requests show the correct content type in the middleware meaning they also print the response fine and others do not? All of them look good in the REST client when inspecting the returned headers.
EDIT: Some more info discovered tonight while trying to figure this out - if I append any character as a dummy request parameter, it logs the response type correctly:
http://localhost:8081/node/ionmed/api/logout?0 WORKS
where
http://localhost:8081/node/ionmed/api/logout DOES NOT
Also, I can always get a response type logging in the middleware function if I replace the .json() call with .end() so this:
res.json({ item: 'logout', success: true });
becomes:
res.set('content-type', 'application/json');
res.end({ item: 'logout', success: true });

HTML5 localStorage and Dojo

I am working in DOJO and my task is i have one JSON file and the datas are coming from JSON url. So now i have to read JSON url and save the datas to browser using HTML5 localStorage, after saving i have to read datas from browser and i have to display in DOJO. Guys any one know about this kindly help me..
Function for getting json data
function accessDomain(dom_sclapi, handle) {
var apiResponse;
//accessSameDomain
if(!handle) {
handle = "json";
}
dojo.xhrGet({
url : dom_sclapi,
handleAs: handle,
sync: true,
headers: { "Accept": "application/json" },
//Success
load: function(Response) {
apiResponse = Response;
},
// Ooops! Error!
error: function(Error, ioArgs) {
//apiResponse = Error;
//console.log(ioArgs.xhr.status);
}
});
//apiResponse
return apiResponse;
}
where dom_sclapi = <json url>
Call
var data = accessDomain(<jsonurl>,'json');
then
console.log(data);
You can see the json o/p in console window. Now you can dispaly to html page using,
dojo.forEach(data, function(eachData){
//script for each json element eg: eachData.displayName;
});