0

I am not able to download excel file in Nodejs sending API from front end(angular 4). Can anyone please help me here? I am attaching the picture and source code i am using in backend in node js.

Error Screen Shot

app.controllers.getExcel = function (req, res) {

    console.log("------------------------------CHECK===========================")
    console.log("------------------------------CHECK===========================")
    console.log("------------------------------CHECK===========================")
    var include = [app.db.cases];
    var perPage = req.query.limit ? Number(req.query.limit) : 200,//showing 200 record per page
        page = req.query['page'] ? Number(req.query['page']) - 1 : 0,
        query = {};

    if (req.query.case_id) {
        query['case_id'] = Number(req.query.case_id);
    }
    query.status = {"$notIn": ['completed', 'QA-Completed', 'QA-Pending']};
    if(req.role.name == 'lea'){
        query.status = {"$notIn": ['completed', 'waiting', 'inprogress']};
    }
    if (req.query.start_date && req.query.end_date) {
        var date = new Date(req.query.start_date.substr(0, 10));
        var edate = new Date(req.query.end_date.substr(0, 10));
        edate.setDate(edate.getDate() + 1);
        edate = edate.toString();
        query.createdAt = {$gte: date, $lt: edate}
    }
    if (req.query.client_id) {
        query['client_id'] = req.query.client_id;
    }
    if (req.query.company_id) {
        query['company_id'] = req.query.company_id;
    }
    if (req.query.sort) {
        query['sort'] = req.query.sort;
    }

    let w = {}

    if (req.query.cnic || req.query.lastName || req.query.firstName || req.query.fatherName ||
        req.query.city) {
        delete query.status;
        w = {}
        if (req.query.cnic) {
            w['emp_id'] = {"$like": "%" + req.query.cnic + "%"};
        }
        if (req.query.city) {
            w['city'] = {"$like": "%" + req.query.city + "%"};
        }
        if (req.query.fatherName) {
            w['fatherName'] = {"$like": "%" + req.query.fatherName + "%"};
        }
        if (req.query.lastName) {
            w['lastName'] = {"$like": "%" + req.query.lastName + "%"};
        }

        if (req.query.firstName) {
            w['firstName'] = {"$like": "%" + req.query.firstName + "%"};
        }

        include = [
            {
                model: app.db.cases,
                where: w
            }
        ]

    }

    $where = {"$or": [{is_qa: 1}, {vo_updated: 1, qa_verified: 1}, {vo_updated: 1, qa_verified_dt: null}]};

    var requ = false;
    if (req.query.service_id) {
        $where = {}
        $where['vo'] = {"$in": req.query.service_id.split(',')}
        requ = true
    }
    if (req.query.qaStatus && req.query.qaStatus != '') {
        $where['qa_verified'] = req.query.qaStatus;
        delete query.status;
        requ = true
    }
    if (req.query.casetatus && req.query.casetatus != '') {
        $where['v_status_id'] = req.query.casetatus;
        delete query.status;
        requ = true
    }
    if (req.query.leaStatus && req.query.leaStatus != '') {
        $where['lea_status'] = req.query.leaStatus;
        delete query.status;
        requ = true
    }
    if (req.query.status) {
        query['status'] = {$or: req.query.status.split(/(?:,| )+/)};
    }

    include.push({
        model: app.db.CaseVerification,
        where: $where,
        required: requ,
        include: [{
            model: app.db.VerificationStatus,
            required: false
        }, {
            model: app.db.User,
        },]
    })


    CRUD.findPaginationWithRelation(CHECKS, page, perPage, include, async function (err, docs) {
        if (err) {
            return res.send(400, {
                code: 400,
                message: "Database Occurred Error",
                success: false,
                error: err
            });
        } else {
            if (docs) {
                var row = JSON.parse(JSON.stringify(docs.rows));

                for (let i = 0; i < row.length; i++) {

                    if (row[i].vo && row[i].vo > 0) {
                        row[i].VO_USER = await CRUD.findOneSync(app.db.User, {id: row[i].vo});
                    }
                }
                let workbook = new excel.Workbook(); //creating workbook
        let worksheet = workbook.addWorksheet('Customers'); //creating worksheet

        //  WorkSheet Header
        worksheet.columns = [
            { header: 'Id', key: 'id', width: 10 },
            { header: 'Name', key: 'name', width: 30 },
            { header: 'Address', key: 'address', width: 30},
            { header: 'Age', key: 'age', width: 10, outlineLevel: 1}
        ];
        worksheet.addRows(row);

        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        res.setHeader('Content-Disposition', 'attachment; filename=' + 'customer.xlsx');

        return workbook.xlsx.write(res)
              .then(function() {
                    res.status(200).end();
              });
                res.send({
                    code: 200,
                    success: true,
                    message: "SuccessFully Find",
                    CHECKS: row,
                    page: page + 1,
                    totalPages: Math.ceil(docs.count / perPage),
                    count: docs.count
                });
            } else {
                console.log('--------------------------EMPTY DOC--------------------')
                res.send({
                    code: 200,
                    success: true,
                    message: "SuccessFully Find",
                    CHECKS: [],
                    page: page + 1,
                    totalPages: 0,
                    count: 0
                });
            }
        }
    }, query)
};

Unhandled rejection Error: Can't set headers after they are sent.

1 Answers1

0

About the error "Unhandled rejection Error: Can't set headers after they are sent." you can find a good explanation at Error: Can't set headers after they are sent to the client

However, I believe this isn't the problem. TypeError: res.status(...).end is not a function error is the problem. The method "end" was removed from express 5.x. An alternative would be res.status(status).send(http.STATUS_CODES[status])

  • I am not using express.js. I am using angular 4 – Vinhaar iqbal Oct 03 '19 at 11:51
  • @Vinhaariqbal I am not following you. The error you got is from NodeJS and not for angular 4. That been said, you send as params the req and res objects into you getExcel function and res.status(...) doesn't have function end. To access the end() you have to use res.end(...); Reference: https://nodejs.org/api/synopsis.html – Diogo Ferraz Oct 03 '19 at 14:54