473,327 Members | 1,919 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

How to retrieve JSON response data from POST request in nodejs

31
I'm performing some encryption in my server (express routing in node) through a post request:

Expand|Select|Wrap|Line Numbers
  1. app.post('/encrypt', encrypt);
Encrypt is doing:

Expand|Select|Wrap|Line Numbers
  1. function encrypt(req,res) {
  2.         if(req.body.key && req.body.message) {
  3.             var encryptedMessage = Encrypter.encrypt(req.body.key,req.body.message);
  4.  
  5.             return res.status(200).json({ message: encryptedMessage });
  6.          }
  7.  
  8.          res.status(409).json({ message: 'the message could not be encrypted, no key found' });
  9.         }
  10.     }
So, I tested this via console.log, and it's working. When the server receives the request, the encrypted message is being generated.

At the same time, I'm testing my thing with mocha and I'm doing it like so:

Expand|Select|Wrap|Line Numbers
  1.     describe('# Here is where the fun starts ', function () {
  2.       /**
  3.        * Start and stop the server
  4.        */
  5.       before(function () {
  6.         server.listen(port);
  7.       });
  8.  
  9.       after(function () {
  10.         server.close();
  11.       });
  12.  
  13.       it('Requesting an encrypted message', function(done) {
  14.         var postData = querystring.stringify({
  15.           key : key,
  16.           message : message
  17.         });
  18.  
  19.         var options = {
  20.           hostname: hostname,
  21.           port: port,
  22.           path: '/encrypt',
  23.           method: 'POST',
  24.           headers: {
  25.             'Content-Type': 'application/x-www-form-urlencoded',
  26.             'Content-Length': postData.length
  27.           }
  28.         };
  29.  
  30.         var req = http.request(options, function(res) {
  31.           res.statusCode.should.equal(200);
  32.           var encryptedMessage = res.message;
  33.           encryptedMessage.should.not.equal(message);
  34.           done();
  35.         });
  36.  
  37.         req.on('error', function(e) {
  38.           //I'm aware should.fail doesn't work like this
  39.           should.fail('problem with request: ' + e.message);
  40.         });
  41.  
  42.         req.write(postData);
  43.         req.end();
  44.       });
  45.     });
So, whenever I execute the tests, it fails with `Uncaught TypeError: Cannot read property 'should' of undefined` because res.message does not exist.

None of the res.on (data, end, events is working, so I suppose the data should be available from there. First I had this:

Expand|Select|Wrap|Line Numbers
  1.    var req = http.request(options, function(res) {
  2.       res.statusCode.should.equal(200);
  3.       var encryptedMessage;
  4.  
  5.       res.on('data', function (chunk) {
  6.         console.log('BODY: ' + chunk);
  7.         encryptedMessage = chunk.message;
  8.       });
  9.  
  10.       encryptedMessage.should.not.equal(message);
  11.       done();
  12.     });
  13.  
But res.on was never accessed (the console.log didn't show anything). I'm therefore a bit stuck here. I'm surely doing some basic stuff wrong, but I don't have a clue, and the many questions I found doesn't seem to apply to my case.

Weird enough, if I launch a test server and then I curl it
Expand|Select|Wrap|Line Numbers
  1.  curl --data "key=secret&message=veryimportantstuffiabsolutellyneedtoprotect" localhost:2409/encrypt
  2.  
Curl justs waits ad aeternam.
Aug 25 '15 #1
3 1748
Dormilich
8,658 Expert Mod 8TB
it looks like your test setup is insufficient. (additionally, in your code you use variables nowhere defined). since I’m not familiar with testing Node I can only refer you back to the sources where your test setup is explained.
Aug 25 '15 #2
Sieira
31
Thank you for your kind help

Actually, this is not the complete code, just a simplification. All the variables are defined, otherwise I'd be getting an ECCONREFUSED or similar. As far as I know, the tests are properly configured. I can perform GETS without problems, following the same method, and my POST is sending an answer, but not the data within. You can take a look at the complete code here:

Test (from line 375) -> https://github.com/sieira/sereno/blo.../test/index.js

Encryption (line 43) -> https://github.com/sieira/sereno/blo...no-strategy.js

Test server -> https://github.com/sieira/sereno/blo...test/server.js

Then, I'm still stuck with this...
Aug 26 '15 #3
Sieira
31
Actually I was doing it properly at the beginning, and the problem was that I was "clearing" my context with done() before the post data arrived. The solution is:

Expand|Select|Wrap|Line Numbers
  1.   var req = http.request(options, function(res) {
  2.     res.statusCode.should.equal(200);
  3.  
  4.     res.on('data', function(data) {
  5.       encryptedMessage = JSON.parse(data).message;
  6.       encryptedMessage.should.not.equal(message);
  7.       done();
  8.     });
  9.   });
In such a way that done() is only called when the data has been threated. Otherwise, mocha will not wait for the answer.
Aug 26 '15 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Pavils Jurjans | last post by:
Hallo, I am working on multilingual web-application, and I have to be very sure about how the international characters are encoded and decoded in the client-server form requests. There's a...
4
by: James Johnson | last post by:
Dear C#Dex, I am trying to automate a POST to a web page that clicks a button. I have been able to hit a target web page and run the web page. However, the button on the page does not click. ...
1
by: Alex Nitulescu | last post by:
I have the following very simple colde (while learning about cookies and session state): Private Sub cmdAddCookie_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles...
4
by: figelwump | last post by:
All, I am writing an HTTP 1.1 compliant proxy in c#.NET, for use as a proxy server for any web browser (IE, firefox, etc). I've got it working fine for GET requests. However, when a POST...
2
by: MDANH2002 | last post by:
Hi From VB.NET I want to simulate the POST request of the following HTML form <html> <title>HTTP Post Testing</title> <body> <form action=http://www.example.com/postdata ...
4
by: Amuthaangler | last post by:
Hi all, I am currently working with Iframe which holds the JSON response from the server once when the picture gets uploaded successfully. Now I need to parse the JSON response and retrieve...
1
by: MichaMicha | last post by:
Hi, I'm experiencing some problems when I get a huge Json response. Is there a way to increase the maximum size of a response?
2
by: robertybob | last post by:
Hi I am retrieving a JSON response for a menu (via NewtonSoft) and am successfully parsing it for use. The problem is that the end data I need could be 3 levels down or could be 7 levels down....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.