Friday, 26 May 2017

Can't set headers after they are send even not using writehead

So I have this route:

PostArticle: (req, res) => {
    _processFormData(req, res,
        (req, res, article) => { //onSuccess
            try {
                    myCart.addArticle(article);
                    _GetAllArticles(req, res);
            } catch (ex) {
                console.log(ex);
            }
        });
},

Here is my processFormData:

 function _processFormData (request, res, onSuccess,onError) {
    var requestBody = '';
    request.on('data', function (data) {
        requestBody += data;
        if (requestBody.length > 1e7) {
            res.writeHead(413, 'Request length too long', { 'Content-Type': 'text/html' });
            res.end('413 : Request Entity Too Large');
        }
    });

    request.on('end', function () {     
        var oFormData = qsLib.parse(requestBody);
        onSuccess(request, res, oFormData);             
    });

    res.end();
}

And finally _getAllArticles:

function _GetAllArticles(req, res) {
    try {
        var allArticles = myCart.getAllArticles();

        res.setHeader("Content-Type", 'application/json');
       res.setHeader('Cache-Control','no-cache');
        res.write(JSON.stringify(allArticles));
        res.end();

    } catch (ex) {
        console.log(ex);
    }
}

The problem is every time I call "PostArticle" I come to GetAllArticles and there I get always the exception that I cant set header after they are being send.

Here is where I call my route:

function postQueryHttpCall() {

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/articlePost', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            JSON.parse(this.responseText); //Unexpected end of JSON input
        }
    }

    var artName = document.getElementById("name");
    var artPrice = document.getElementById("price");
    var artQuant= document.getElementById("quantity");
    var imagLoc = document.getElementById("imageLocation");
    var desc= document.getElementById("description");



    xhr.send(artName.title + "=" + artName.value + "&" + artPrice.title + "=" + artPrice.value + "&" + artQuant.title + "=" + artQuant.value
        + "&" + imagLoc.title + "=" + imagLoc.value + "&" + desc.title + "=" + desc.value);
}

After "receiving" the data I get the error: Unexpected end of JSON input. What am I doing wrong?



via Lebron11

No comments:

Post a Comment