I am using the Node.js framework and Express module to write an API wrapper that redirects requests to another server. I can successfully redirect the request to the target server and I receive a valid response containing a JSON payload. However, after the initial request, if I try another request I get the following error.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
This is a sample of the code I wrote for the HTTP GET Express route:
app.get('/companyrecords/:name', function(req, res) {
const options = {
protocol: 'http:',
hostname: 'myhost',
port: 5001,
method: 'GET',
path: '/path/to/resource/?name=name',
auth: 'username:password',
headers: {
Connection: 'close'
}
}
const myAppReq = http.request(options, (myAppRes) =>{
console.log(`STATUS: ${myAppRes.statusCode}`);
myAppRes.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
res.send(chunk);
});
myAppRes.on('end', () => {
res.end('No more data to send.');
});
});
myAppReq.on('error', (err) => {
console.error(`Problem with request: ${err.message}`);
});
myAppReq.write('');
myAppReq.end();
});
Not sure why I am getting this error since I am calling the req.write() method so that the request's headers are sent. When looking at the error stack trace it appears the error occurs when I call the res.send() method inside the callback to the 'data' event. Perhaps I'm not understanding the flow of execution among the request or the sequence in which the events are being emitted. Any guidance/information would be greatly appreciated.
You shouldn't be sending the response inside data
event callback because response will be sent when you will receive the first chunk of data. What you should do is to write the chunk
to response stream and send response inside end
event callback:
const myAppReq = http.request(options, (myAppRes) =>{
myAppRes.on('data', (chunk) => {
res.write(chunk);
});
myAppRes.on('end', () => {
res.end();
});
});