how to read ajax data in my nodejs express server - ajax

My webpage is able to get ajax data with the following code
$.ajax({
type: 'POST',
url: "/get_cache_transactions",
async: true,
data:
JSON.stringify({
a: 11,
b: 22,
c: 33
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) { process_cache_changes(data) },
error: function (xhr, ajaxOptions, thrownError) { }
})
but on the node express server can't read the parameter a, b, or c from the web page.
The nodejs express code is as follows
var express = require('express');
var app = express();
var handlebars = require('express-handlebars').create({ defaultLayout: 'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.use(require('body-parser').urlencoded({ extended: true }));
app.post('/get_cache_transactions', function (req, res) {
console.log("************************************************************************************************")
>>> how to I get value of a, b, c ?????
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(pic_cache.cache, null, 2));
});
I tried printing out all of the attributes of req and nothing appears to contain a,b,or c. I tried to look at req.body and again nothing.
for (i in req.body){console.log(i)}
Also, my dependencies for this project are
"dependencies": {
"body-parser": "^1.15.1",
"cookie-parser": "^1.4.3",
"express": "^4.13.4",
"express-handlebars": "^2.0.1",
"express-session": "^1.13.0",
"formidable": "^1.0.17",
"fs": "0.0.2",
"parseurl": "^1.3.1"
},
in the chrome debugger (f12), i select network and see the following for the Post
General
Request URL:http://localhost:1662/get_cache_transactions
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:1662
Response Headers
view source
Response Headers
Connection:keep-alive
Content-Length:631
Content-Type:application/json; charset=utf-8
Date:Sun, 26 Jun 2016 20:31:40 GMT
ETag:W/"277-PiWC2Y6iMvjEI1tGjkMrcw"
Request Headers
view source
Request Headers
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:22
Content-Type:application/json; charset=UTF-8
Cookie:connect.sid=s%3AOgJ3NCHzZpte0fSsxdLRDHK6Dggql1nC.entV9uoy%2BAHG5C3rNmt%2BrzdbZ9RDwDr%2B2FAqdx5%2BZKk
Host:localhost:1662
Origin:http://localhost:1662
Referer:http://localhost:1662/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
view source
{a: 11, b: 22, c: 33}
a
:
11
b
:
22
c
:
33
So we know the a,b,c are being sent.

You are sending the data in JSON format. Try below code snippet for using the body-parser middleware & accessing the required values
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.post('/get_cache_transactions', function (req, res) {
var a = req.body.a;
var b = req.body.b;
var c = req.body.c;
//Rest of the code
})

Client
$.ajax({
type: 'POST',
url: "/get_cache_transactions",
data: {
a: 11,
b: 22,
c: 33
},
dataType: 'json',
success: function (successResponse) { },
error: function (errorResponse) { }
});
Server
app.post('/get_cache_transactions', function (req, res) {
var a = req.body.a; // same for b and c
res.json(pic_cache.cache);
});

Related

NodeJS Post multipart data (Image Upload)

Hello I want to upload photo from my computer to https://generated.photos/anonymizer , I keep getting alert error in bodyz "Empty message body supplied with multipart form-data", Please help me with coding.
I want it to work like that https://i.imgur.com/CE6i4pE.png
var request = require("request");
var upfile = 'src/All/1.jpeg';
fs.readFile(upfile, function(err, content){
if(err){
console.error(err);
}
let url = "https://api.generated.photos/api/frontend/v1/images/similars";
let data = "";
data += "------WebKitFormBoundaryVIBbTfQEhARYeJqm" + "\r\n";
data += "Content-Disposition: form-data; name=\"file\"; filename=\"zeta\"\r\n";
data += "Content-Type: image/jpeg\r\n\r\n";
let payload = Buffer.concat([
Buffer.from(data, "utf8"),
new Buffer(content, 'binary'),
Buffer.from('\r\n------WebKitFormBoundaryVIBbTfQEhARYeJqm\r\nContent-Disposition: form-data; name=\"per_page\"\r\n\r\n1\r\n------WebKitFormBoundaryVIBbTfQEhARYeJqm--', "utf8"),
]);
let options = {
method: 'post',
url: url,
headers: {"Authorization": "API-Key Cph30qkLrdJDkjW-THCeyA", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36","Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryVIBbTfQEhARYeJqm" , "Content-Length": content.length },
body: payload,
};
request(options, function(error, response, bodyz) {
alert(bodyz);
// after i make it work i will do
// var response_data_parsed = JSON.parse(bodyz);
// alert(response_data_parsed.images.thumb_url)
});
});
Remove
"Content-Length": content.length
And all working. Thanks anyway

Internal server error 500 for all requests to Google Ads API

Here is my code in Node JS.
var bearerToken = 'Bearer '+ access_token;
var options = {
url: 'https://googleads.googleapis.com/v1/customers/'+accountid+'/googleAds:search',
headers: {
'Authorization': bearerToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
'login-customer-id': '123-456-7890',
'developer-token': 'XXX_XXXXXXXXXXX'
},
form: { 'query': 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id' }
};
request.post(options, function(err, response) {
console.log(response);
});
I keep getting the below error
body: '{\n "error": {\n "code": 500,\n "message": "Internal error encountered.",\n "status": "INTERNAL"\n }\n}\n' }
500 error code means the error is from Google. Is this the case or am I doing something wrong here?
After breaking my head with multiple iterations. Finally, I figured out that the problem was with the developer-token. I had to generate a new developer-token and change form to json. It's working fine now.
Here is the final working code
var bearerToken = 'Bearer '+ access_token;
var options = {
url: 'https://googleads.googleapis.com/v1/customers/'+accountid+'/googleAds:search',
headers: {
'Authorization': bearerToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
'developer-token': 'XXX_XXXXXXXXXXX'
},
json: { 'query': 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id' }
};
request.post(options, function(err, response) {
console.log(response);
});

Dojo XhrPost set name for posted json object on server

I have a Dojo ajax request and i am posting the data as json however the data is not reaching the server in json format. I am also not able to see the JSON tab in the browsers Net option of the console. I need the data in json format on the server.
Ajax Request
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
function SendData() {
var xhrArgs = {
url:'processData',
postData: someData,
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);
Screenshot of server details
I would like the JSON data under to appear in the following format under with the name MyData. How is this format possible on the server?
JSON
MyData [Object{id:"1",age:"44",name:"John"},
Object{ id:"2",age:"25",name:"Doe"},
Object{ id:"3",age:"30",name:"Alice"}]
SOURCE
{"MyData":[{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}]}
Actually url:'' is empty in your Ajax call. Please provide action url,
for suppose
url: "AddTrackServlet"
After playing around with the variable i saw it could be declared
var someData = [{id:"1",age:"44",name:"John"},
{ id:"2",age:"25",name:"Doe"},
{ id:"3",age:"30",name:"Alice"}];
var formData = {MyData:someData}
function SendData() {
var xhrArgs = {
url:'processData',
postData: dojo.toJson(formData),
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
load:function(data){
console.log('data was posted');
},
error:function(error){
console.log(error);
}
};
dojo.xhrPost(xhrArgs);

IE lags on sending POST data

Recently I found very strange behavior of IE8/9 when sending XHR data. I'd like to ask you if you have ever seen such behavior? Is it IE bug? How can I protect my server from "empty" request generated by IE? Here are more details:
I found out that when your page tries to send XHR data and JavaScript freezes or lags browser, IE lags sending POST data to server. To make it clear, here are steps to reproduce:
Create simple server which dumps POSTs received. I've used Node.JS for tests. You can find corresponding codes at the bottom of the post.
Open localhost:8080 in IE, open debug window and start debuging scripts with breakpoint set in line 51 of file localhost:8080
Hit Send by JQuery. You should have your javascript waiting on the breakpoint and server logged message:
--------------------------------------
14:04:19
REQUEST: /
HTTP HEADER:
accept = text/html, application/xhtml+xml, */*
accept-language = pl-PL
user-agent = Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
accept-encoding = gzip, deflate
host = localhost:8080
connection = Keep-Alive
--------------------------------------
14:04:35
REQUEST: /test
HTTP HEADER:
accept = */*
content-type = application/json
x-requested-with = XMLHttpRequest
referer = http://localhost:8080/
accept-language = pl
accept-encoding = gzip, deflate
user-agent = Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
host = localhost:8080
content-length = 24
connection = Keep-Alive
cache-control = no-cache
When you release JavaScript from the breakpoint server reports incoming data by new line:
POST: {"data1":10,"data2":123}
I've done the same test on Opera 12.15 and Chrome 27.0.1453.94 m and, as expected, POST data are sent immediately.
-- source codes --
Code for node.js server:
var http = require('http');
var qs = require('querystring');
var fs = require('fs');
http.createServer(function (req, res) {
console.log('--------------------------------------');
console.log(new Date().toLocaleTimeString());
console.log('REQUEST: ' + req.url);
console.log('HTTP HEADER: ');
for (var header in req.headers) {
console.log(' ' + header + ' = ' + req.headers[header]);
}
switch (req.method) {
case 'POST':
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function() {
console.log('POST: ' + body);
});
res.writeHead(200, {'Content-type': 'application/json'});
res.end(JSON.stringify({ succeeded: true, value: 'Hello world!' }));
break;
case 'GET':
fs.readFile('./servertest.html', function (err, data) {
if (err) {
throw err;
}
res.writeHeader(200, {'Content-type': 'text/html'});
res.end(data);
});
break;
}
}).listen(8080, 'localhost');
console.log('listening on localhost:8080');
Code for servertest.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<button onclick="send()">Send by JQuery</button>
<button onclick="sendXHR()">Send by XHR</button>
</body>
<script type="text/javascript">
var _xhr;
function sendXHR() {
_xhr = new XMLHttpRequest();
new XHRStateChangeListener();
var url = '/testXHR';
var method = 'POST';
_xhr.open(method, url);
_xhr.setRequestHeader("Content-Type", "application/json");
_xhr.send(JSON.stringify({test: 'this is a test', aoawiejf:23423}));
}
function XHRStateChangeListener() {
callback = function() {
var msg;
if (_xhr.readyState == 4 && /200|304/.test(_xhr.status)) {
alert('ready: ' + _xhr.responseText);
}
};
_xhr.onreadystatechange = callback;
}
function send() {
$.ajax({
url: '/test',
type: 'POST',
data: JSON.stringify({data1: 10, data2: 123}),
contentType: 'application/json',
error: function(xhr, status, err) {
alert('Error: ' + err + '\nStatus: ' + status);
},
success: function (data) {
alert('succeeded! data: ' + data);
}
});
}
</script>
</html>
You are using sync-mode, right is async-mode:
replace
_xhr.open(method, url);
by
_xhr.open(method, url, true);//Async mode
Note: Remember "onreadystatechange" is only for async-mode
the problem may also be in this function (just a guess):
JSON.stringify
try sending empty data, ie: data:""

Post jQuery JSON Object to NodeJs Restify

I want to know why it is so hard to post a simple JSON string in a /:parameter to restify. I have followed many examples but have not found anything concrete.
I have the following code in the front end.
$("#btnDoTest").click(function() {
var jData = {
hello: "world"
};
var request = $.ajax({
url: "http://localhost:8081/j/",
async: false,
type: "POST",
data: JSON.stringify(jData),
contentType: "application/javascript",
dataType: "json"
});
request.success(function(result) {
console.log(result);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
I am succesful in sending simple text if I concatenate the param after the j/. But what I want to send is an object like this {hello:"world"} and reconstruct it back in nodeJS and work with it.
--Edit:
This is my nodejs file
/* the below function is from restifylib/response.js */
var restify = require("restify");
/* create the restify server */
var server = restify.createServer({
});
server.use(restify.bodyParser({ mapParams: true }));
server.use(
function crossOrigin(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
return next();
}
);
server.post('/j/', function (req, res, next) {
//res.send(201,"REceived body: "+JSON.stringify(req.params));
res.send(201,"REceived body: "+JSON.stringify(req.params));
return next();
});
var port = 8081;
server.listen(port);
console.log("Server listening on port " +port)
Any help would be appreciated thanks.
0x
I finally got it working.
--Front end code
$("#btnDoTest").click(function() {
var request = $.ajax({
url: "http://localhost:3000/j",
async: false,
type: "POST",
data: {
blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
},
contentType: "application/x-www-form-urlencoded", //This is what made the difference.
dataType: "json",
});
request.success(function(result) {
console.log(result);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
NodeJs services
/* the below function is from restifylib/response.js */
var restify = require("restify");
/* create the restify server */
var server = restify.createServer({
});
server.use(restify.bodyParser());
server.use(restify.CORS());
server.post('/j/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
// req.params == data on jquery ajax request.
res.send(200, JSON.stringify(req.params));
console.log(req.params.blob.ar[2].a)
res.end();
return next();
});
var port = 3000;
server.listen(port);
console.log("Server listening on port " + port)
Don't stringify it. Try this, note the two changes, I removed the JSON.stringify and switched to application/json, as its JSON and not JavaScript.
var request = $.ajax({
url: "http://localhost:8081/j/",
async: false,
type: "POST",
data: jData,
contentType: "application/json",
dataType: "json"
});
application/javascript should only be used when doing JSONP.
my answer first!
jquery:
$.ajax({
url: url,
method: 'post',
data: JSON.stringify({key:value}),
contentType: "application/json"
});
node http:
server.post('/1', function(req, res) {
var body = req.body;
var dataValue = body.dataKey;
});
why?
data of $.ajax is just for what to send to server end, its datatype has not be defined, so when use JSON.stringify({key:value}), the data will be sent as a string like '{key:"xxx"}', and node recieve a string, not a json object even the string structure looks like a json. but after we add contentType: "application/json" in $.ajax, when node recieve the data, it will be a real json object type data.

Resources