473,403 Members | 2,284 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,403 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 1752
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...

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.