Tuesday 6 June 2017

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after th y are sent

I'm just new to Node. I use express.js There is a part of my code, where I'm tring to get data that I got from form by AJAX and write this to variable 'url'. I have request.body, but I can't pass it to "then". Instead of it I have an error "UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent". Could you tell me what am I doing wrong? Thanks a lot.

    app.get('/', function (req, res) {
        return res.render('index.html').end();
    });

    app.post("/", jsonParser, function (request, response) {
        return new Promise((resolve, reject) => {
            if (!request.body) {
                reject()
            } else {
                console.log(request.body);
                response.json(`${request.body.url}`);
                url = response.json(`${request.body.url}`);
                resolve(url);
            }
        }).then(data => console.log(data));
    });



via Konstantin

No comments:

Post a Comment