![]() ![]() The request handler function already sent a response to the client using the res.json() method which automatically sets the response header(every response to the client should contain headers) for the response(in this case the Content-Type to application/json). ![]() Looking at the code logic you'd aggree that the request handler function has no explicit command for exiting the function in a situation a reqest body is not found and the error response is sent back to the client, therefore after the if statement condition has being resolved the server tries to send another response to the client and this is where the error kicks in. The request handler(the anononymous function that takes the req & res arguements) is simply a javascript function and this means that the javascript engine(v8 in nodes case) keeps executing the code beyond the if statement when there is no explicit instruction for it to exit the function. The expectation is that the request handler should do what we've programmed it to do (return response to the client). This case study is based on a simple POST request to a /test route using the express framework.īy design the server should send back a 400(Bad request) JSON response to the client if a request does not have a body(req.body) added to the request to ther server from the client (handled with the javascript if statement) and lastly if the request comes with a body a 200(OK) JSON respresention of the request body is sent back to the client as response. What this means is that for a given client request the server previously sent a response (either a success responsei with the resource requested or error response for a bad request) back to the client and now is unexpectedly trying to send another response talk is cheap const express = require('express') Ĭonst bodyParser = require('body-parser') Uncovering the mysteryĮrror is an interesting error that is fired up when a server tries to send more than one response to a client. SPOILER ALERT: I have run into this runtime error couple times while building restful API's and this is an effort to document what i learnt about this error, shorten your debugging time, help you understand why this error is thrown and finally how best to handle it. Now you begin to ask yourself why you even choose this career path or even why you picked up node in the first place. ![]() You must have written the perfect code and expect a flawless code excution (i wish ), but here is this runtime error shattering your expectations and definitely keeping you from moving on to other concerns of your project. : Cannot set headers after they are sent to the client Chances are as a NodeJS developer you've encountered this runtime error: ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
January 2023
Categories |