Is it required to send a response in every request no matter GET or POST in nodejs? - node.js

I defined my_function inside app.post('/someRoute',my_function) in nodejs which is used for making an http-request(posting data) to another server.
However it seems that my_function will run twice when I do not defined any response to the browser inside my_function.
What will be the reason for this? And is it required to send a response in every request no matter GET or POST in nodejs?
Thanks!

Whenever you do not define a response to a function/route handling get or post requests, the request response cycle will not end and thus the request keeps running until it times out because it took too long to get a response from the server. It is thus important to define a response to every request.

Related

Why do we need to add .end() to a response?

Currently building a RESTful API with express on my web server, and some routes like the delete route for a document with mongoose ex. await Note.findByIdAndRemove(request.params.id) response.status(204).end() send response statuses with end()
Why do I need to add the .end()? What in these cases, and why cant one just send response.status(204)
With some responses that return json, the response.status(201).json works fine
Only certain methods with Express or the http interface will send the response. Some methods such as .status() or .append() or .cookie() only set state on the outgoing response that will be used when the response is actually sent - they don't actually send the response itself. So, when using those methods, you have to follow them with some method that actually sends the response such as .end().
In your specific example of:
response.status(204)
You can use the Express version that actually sends the response:
response.sendStatus(204)
If you choose to use .status() instead, then from the Express documentation, you have to follow it with some other method that causes the response to be sent. Here are examples from the Express documentation for .status():
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')
Since all three of these other methods will cause the response to be sent and when the response goes out, it will pick up the previously set status.

Use result of post in a subsequent post request

I'm a newbie and have little knowledge, I apologise in advance.
I have been trying to find examples on making subsequent post requests using data from the first request.
Scenario, making a request to obtain an auth token which will then be used on subsequent requests in the header.
E.g. request 1 is a POST and returns an access_token object
request 2 is a POST and requires the access_token object from request 1 in the headers.
I have successfully made the request 1 with request-promise but don't know how to pass that to the 2nd requests options.
Thanks
Look into "promise chaining". You should make the second request in the .then((resp) => ...) callback, where you have access to the response data from the first request. If you return the second request promise, you can continue the chain.

Node Express Can't set headers after they are sent In case of Multiple Request

My Application works perfectly fine untill I send multiple (2 or more) request simultaneously. As soon as I send multiple requests Express throws
Error: Can't set headers after they are sent.
Its a long code, where its takes almost 2 seconds to execute complete request . If I send multiple requests (where response time is pretty fast) i dont face this issue?
I know the reason why and when express throws 'Can't set headers' error. My main point is to understand how I can debug my application in this scenario as everything works fine incase of single request and it breaks down incase of multiple requests.
The error means that you're already in the Body but later in the code some function tried to set a header or statusCode. When you see this error, try to look the code for any improper callbacks or exception scenarios in which the response object is referenced multiple times.
Usually it must be next() called twice .

Fetch post data after a request in NodeJS

i' m a bit new to Node, so question may be stupid...
I am sending a POST request to a website (through http.request) and I want to be able to use the invisible POST data I get along the response.
I hope this is achievable, and I think so since I am able to preview those data in Chrome debugger.
PS : I understand that we can use BodyParser to parse and get those while listening for a POST call server side, but I have found no example of how to use it coupled with an http.request.
Thanks !
If the body of the HTTP response contains JSON, then you need to parse it first in order to turn it from a string into a JavaScript object, like this:
var obj = JSON.parse(body);
console.log(obj.response.auth_token);
More info on various ways of sending a POST request to a server can be found here: How to make an HTTP POST request in node.js?
Edit : So we figured it out in the comments. The value I needed was in the form to begin with, as a hidden field. My error was to think it was generated afterward. So I'll just grab it first then login, so I can use it again for future POST requests on the website.

node.js parallel requests are crashing node app - can't render headers

Ways to replicate the problem,
A. continuously refresh the browser (cmd+r) and then the app crashes with the following message
B. run mocha test suite, inside I'm using npm module request for http request and all of them pass, however as soon as I send another request in parallel using postman while the tests are running, then the app crashes with the following message.
http.js:731
throw new Error('Can\'t render headers after they are sent to the client.'
^
Error: Can't render headers after they are sent to the client.
at ServerResponse.OutgoingMessage._renderHeaders (http.js:731:11)
at ServerResponse.writeHead (http.js:1152:20)
at puremvc.define.signInWithCredentialsSuccess (eval at include (/Library/WebServer/Documents/FICO/fico-node/app.js:3:32), <anonymous>:31:18)
the code referenced
signInWithCredentialsSuccess: function(request, response, authToken) {
response.writeHead(200, {'Content-Type': 'text/xml'})
response.end(this.mustache.render(this.successTemplate, {authToken: authToken}));
},
It's an express application combined with puremvc, so architecture is a bit different, for instance after app.get, the request and response are passed around to different decoupled modules and functions who accomplish their tasks and simply end the response by writing some output and then the process is repeated again for each subsequent request using new response/request objects passed.
I assume that I should be getting a new request and response object for each request but the error message confuses that for some reason the app.get is giving me a reference to an old response object which was already used to sent the information down to the client that's why it's refusing to modify the headers.
my node version is 0.10.32
please advise

Resources