Why does http header error show up and where is the flaw?

Issue

I was trying to get XML and parse it to JSON. There are 2 files of included here.
But I keep getting this error. I’ve tried to look around SO and still doesn’t get answers.

main.js

/** SET ENGINE TO PUG */
app.set("views", path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
    
/** ROUTES */
app.get('/', (req, res) => {
    res.render('index',{title: 'HOMEPAGE'});
})

app.get('/json_results', (req, res, next) => {
    res.render('json_results', {title: 'NEWS TODAY', json_results_in: 
        getJson.produce_xml(url, function (err, data) {
            if (err) {
                return console.error(err);
            }
            res.json(JSON.stringify(data, null, 2));
        })
    });
});

get_json.js

var express = require('express');
var https = require('https');

/** PARSE XML TO JSON */
var parsedtext = require('xml2js').parseString;

function xmlToJson(url, callback) {
    var req = https.get(url, function(res) {
        var currentXml = '';

        res.on('data', function(chunk) {
            currentXml += chunk;
        })

        res.on('error', function(err) {
            callback(err, null);
        })

        res.on('timeout', function(err) {
            callback(err, null);
        })

        res.on('end', function() {
            parsedtext(currentXml, function(err, result) {
                callback(null, result);
            })
        })
    });
}

module.exports.produce_xml = xmlToJson

and the error I get is

code: ‘ERR_HTTP_HEADERS_SENT’

Please enlighten me. Thank you in advance.

Solution

res.render sends a response (an HTML document generated from pug in this case) to a request.

res.json also sends a response (some JSON) to a request.

A response consists of a header and, usually, a body.

A request can only have one response.

When you call res.json you are trying to send a new response, starting with the headers (hence the error message), to a request to which you have already responded.

Answered By – Quentin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published