Receving POST request from Node JS server on Arduino - javascript

Im trying to send a post request to an arduino with Node JS and the Request package:
var body = {
d:"5",
l:"6",
TOTAL_VOLUME: "75",
meterId: "9"
};
var options = {
url: 'http://'+'192.168.1.102'+'/configData',
timeout: 7000,
headers: {
'Content-type' : 'application/json',
'Content-length': JSON.stringify(body).length
},
json:true,
body: JSON.stringify(body)
};
request.post(options, function (error, response, body) {
//console.log(error);
//console.log(response);
console.log(body);
if (!error && response.statusCode == 200) {
console.log("Changed configuration succesfully. ");
// Request to enpoint to save changes in database
var options = {
url: 'http://'+'8.8.8.8:4000'+'/meter/'+meter.id+'/',
method: 'PUT',
timeout: 10000,
body: {
'tank_diameter': tank_diameter,
'tank_length':tank_length,
'tank_capacity': tank_capacity
}
};
/*request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
}
});*/
}
done();
}).on('error', function(err) {
console.log(err);
done();
});
The above code is how I send the data, However Im not able to get the data on the arduino.
This is the code on arduino:
server.on("/configData", HTTP_POST, [](){ // configData Seteo de Valores desde POST
StaticJsonBuffer<200> configBuffer;
JsonObject& configJson= configBuffer.parseObject(server.arg("plain"));
String l = configJson["l"];
String d = configJson["d"];
String meterId2 = configJson["meterId"];
String volumenTotal = configJson["TOTAL_VOLUME"];
LENGTH = l.toFloat();
HEIGHT = d.toFloat();
meterId = meterId2.toInt();
TOTAL_VOLUME = volumenTotal.toFloat();
// GUARDAR EN LA EEPROM
int EEadr = 0;
EEPROM.write(EEadr, HEIGHT);
EEPROM.commit();
EEadr = 10;
EEPROM.write(EEadr, LENGTH);
EEPROM.commit();
EEadr = 20;
EEPROM.write(EEadr, TOTAL_VOLUME);
EEPROM.commit();
EEadr = 30;
EEPROM.write(EEadr, meterId);
EEPROM.commit();
//SHOW ON SERIAL MONITOR
Serial.println("l= "+l);
Serial.println("d= "+d);
Serial.println("meterId2= "+meterId2);
Serial.println("TOTAL_VOLUME= "+volumenTotal);
server.send ( 200, "text/json", "{success:true}" );
});
The weird thing is that if I use curl like this:
curl -H "Content-type: application/json" -X POST -d "{l:\"55\", r:\"10\", meterId: \"2\"}" http://192.168.1.2
The arduino does receive the data correctly, so the problem is most likely on my Node JS request. Can anyone tell me what Im I doing wrong here?
UPDATE:
Ive checked the requests with wireshark, and it results that the curl request (the one that is working) is being sent as Line based text data. Can anyone tell me how can I send it the same way using Node JS and request?

In these type of situations you can check your request structure with applications like wireshark.
In this problem if you can see that you attach your hole json as a single string, because when you set json flag of request in request library it convert your body into json for you so now you have something like:
var options = {
body: JSON.stringfy(JSON.stringfy(body))
};
so you can correct your application by simply set following options:
var options = {
url: 'http://'+'www.goole.com'+'/configData',
timeout: 7000,
json:true,
body: body
};

Related

Header section has more than 10240 bytes (maybe it is not properly terminated)

I'm using NodeJs to try to upload an attachment to a Jira Issue via the Jira Rest API.
The api expects multipart/form-data so this is how I'm calling it in Node:
function uploadAttachments(supportFormData, callback) {
const url =
'https://somewhere.com/jira/rest/api/2/issue/' +
supportFormData.issueId +
'/attachments';
var options = {
url: url,
headers: {
Authorization: { user: username, password: password },
'X-Atlassian-Token': 'nocheck'
}
};
var r = request.post(options, function(err, res, body) {
if (err) {
console.error(err);
callback(false);
} else {
console.log('Upload successful! Server responded with:', body);
callback(false);
}
});
var form = r.form();
form.append('file', supportFormData.attachments[0].contents, {
filename: supportFormData.attachments[0].fileName,
contentType: supportFormData.attachments[0].contents
});
}
The error I'm receiving is:
org.apache.commons.fileupload.FileUploadException: Header section
has more than 10240 bytes (maybe it is not properly terminated)
The "supportFormData.attachments[0].contents" is ofType Buffer.
Any suggestions as to what could be causing this error?
I ran into this same issue and it turns out JIRA (or Java) requires \r\n as new line character. After I changed \n to \r\n my requests went through without problem.
If its a basic auth change options object to
let auth = new Buffer(`${username}:${password}`).toString('base64');
var options = {
url: url,
headers: {
Authorization: `Basic ${auth}`,
'X-Atlassian-Token': 'nocheck'
}
};

Problem with Github-Api v3 using JavaScript

For a homework (in Signavio Workflow Accelerator) I need to add users to an organization on Github using the GitHub-API v3. The Code has to be written in JavaScript which i a language I'm not very familiar with.
At the moment I get the following error code: "SyntaxError: Unexpected token o in JSON at position 1 at Request._callback". So I have the feeling that there might be a problem with the parsing.
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
request({url: link, method: 'put', headers: {'User-Agent': 'request'}, auth: {username: token}, JSON: true},
function (response, body) {
console.log(body)
if(body !== undefined){
body = JSON.parse(body)
body['state'][0]['main']
status = body['main']['state']
status = body.main.state
}
else{
status = 'error'
}
})
I don't know if this might be helpful, but if I perform this put request using cURL it works and the answer starts with:
{
"url": "https://api.github.com/orgs/myorganization/memberships/githubUser",
"state": "pending",
...}
So this "state" is the value I want to read in the code above.
Already thanks for helping!
I worked together with a friend of mine and together we found a working solution. So if anyone else is having the same struggle: This piece of code does the magic!
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
const options = {
url: link,
method: 'put',
headers: {'User-Agent': 'request'}, auth: {username: token}
}
function callback(error, response, body) {
console.log(error)
if(!error && response.statusCode == 200){
const info = JSON.parse(body)
status = info['state'][0]['main']
console.log(status)
status = info['state']
status = info.state
}
console.log(body)
}
request(options, callback)

Request keeps on getting Error code: 400 - can someone please have a look on what I'm doing wrong?

Spent a few hours trying to solve this but keep on getting 400 errors. I think my payload is incorrect but not sure what I need to do.
I've tried the same request in POSTMAN with great success, and also have tried different combinations on formatting my payload (body).
I've also tried the following: var body = {"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}};
function main(){
// Set the headers
var headers = {
'Authorization': 'Bearer ya29.GlyvBPhT4Y502Yo4NZ6sKI001AYlVU6om5ytXrzf2vjfEYERrsdMSBu-2ZkKir83jjj06-ewqYuBvvrx8mKfuTW1YjjlmtPmRdlK0I0Gjx',
'Content-Type': 'application/json',
'User-Agent': 'Untitled browser'
}
var uri = 'https://language.googleapis.com/v1/documents'+encodeURI(':analyzeSentiment');
var form = JSON.stringify({"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}});
// Configure the request
var options = {
url: uri,
method: 'POST',
headers: headers,
form: form
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
else{
console.log('Error code: '+response.statusCode)
}
})
}
main();
Update - this is how it works in POSTMAN
Header is the same too:
Solved!
Need to post as body rather than form

Post Method works using https.request but not with Needle or Request libraries

I have nodeApp. It does stuff.
At a particular time I need to communicate with an API that out there in the wild. Using the API in rest tool like Postman is straight forward:
Postman
Url:
https://epicurl
Headers:
Content-Type : application/json
Accept : application/json
x-key : secret
Body:
{
"some":"kickass"
"data":"here"
}
Sending the above in Postman I get a nice quick response! Yay for rest tools.
So their API works, now I need to make that same response in my Node.js application.
This is where things get odd...
Request Module: FAILS
var request = require('request')
...lots_of_other_stuff...
var options = {
uri: 'https://epicURL',
method: 'POST',
json: true,
headers : {
"Content-Type":"application/json",
"Accept":"application/json",
"x-key":"secretbro"
},
body : JSON.stringify(bodyModel)
};
request(options, function(error, response, body) {
if (!error) {
console.log('Body is:');
console.log(body);
} else {
console.log('Error is:');
logger.info(error);
}
cb(body); //Callback sends request back...
});
The above fails.. It throws the good'ol ECONNRESET error that we all love! Why? Who knows?
https.request() - WORKS!
var https = require("https");
https.globalAgent.options.secureProtocol = 'SSLv3_method';
var headers = {
"Content-Type":"application/json",
"Accept":"application/json",
"x-key":"nicetrybro"
}
var options = {
host: 'www.l33turls.com',
port:443,
path: "/sweetpathsofjebus",
method: 'POST',
headers: headers
};
var req = https.request(options, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
var resultObject = responseString;
//Call the callback function to get this response object back to the router.
cb(resultObject);
});
});
req.on('error', function(e) {
console.log(e);
});
req.write(bodyString);
req.end();
But then I notice...
If i leave this line of code in place when using the Request Module it then works...
var https = require("https");
https.globalAgent.options.secureProtocol = 'SSLv3_method';
Is this documented somewhere and I am missing it? Anyone explain this to me?

POST to PHP from Node.js

I am trying to POST some data from a Node.js application to a PHP script. For the time being I am just building a proof of concept but I am unable to get the actual data over to the PHP side. The request goes through and I get 200 back but PHP thinks the $_POST array is empty.
Here is my node code:
// simple end point just for testing
exports.testPost = function(request, response) {
data = request.body.data;
postToPHP(data);
response.end(data);
}
function postToPHP (data) {
var http = require('http');
var options = {
host : 'localhost',
port : 8050,
path : '/machines/test/index.php',
method : 'POST',
headers : {
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(data)
}
};
var buffer = "";
var reqPost = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
console.info('POST Result:\n');
//process.stdout.write(d);
buffer = buffer+data;
console.info('\n\nPOST completed');
});
res.on('end', function() {
console.log(buffer);
});
});
console.log("before write: "+data);
reqPost.write(data);
reqPost.end();
}
Again, the request makes it to localhost:8050/machines/test/index.php but when I do a var_dump of $_POST it is an empty array.
[29-Jan-2014 21:12:44] array(0) {
}
I suspect I am doing something wrong with the .write() method but I can't quite figure out what. Any input on what I am missing or doing incorrectly would be greatly appreciated.
* Update:
As some of the comments indicate using file_get_contents('php://input'); does work to get the data on the PHP side but I would still prefer to be able to access the $_POST array directly.
Since you are sending the data with Content-Type: application/json you would need to read the raw input as php does not know how to read json into their globals like _GET and _POST unless you have some php extension that does it.
You can use the querystring library to parse a object into a name-value pair query string that you could than transmit with Content-Type:application/x-www-form-urlencoded so that the data will be parsed into the globals
var data = {
var1:"something",
var2:"something else"
};
var querystring = require("querystring");
var qs = querystring.stringify(data);
var qslength = qs.length;
var options = {
hostname: "example.com",
port: 80,
path: "some.php",
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': qslength
}
};
var buffer = "";
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
buffer+=chunk;
});
res.on('end', function() {
console.log(buffer);
});
});
req.write(qs);
req.end();

Categories