-1

(node:7636) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (C:\Users\username\path\Express\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (C:\Users\username\path\Express\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\username\path\Express\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (C:\Users\username\path\Express\node_modules\express\lib\response.js:158:21)
at body.rows.forEach (C:\Users\username\path\Express\app.js:41:15)
at Array.forEach ()
at db.list.then (C:\Users\username\path\Express\app.js:40:19)
at
(node:7636) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Here is the code for the query:

app.get("/api/customers", (req, res, next) =>{
    res.header("Access-Control-Allow-Origin", "http://localhost");
    res.header("Access-Control-Allow-Methods", "GET, POST");
    res.writeHead(200, {'Content-Type': 'application/json'});
    
    db.list({ include_docs: true }).then((body) => {
        body.rows.forEach((doc) => {
          res.send(doc.doc);
        });
      });
  });

I want to show data on the html page using angularjs.

Any help I will really appreciate.

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
sikaili99
  • 532
  • 6
  • 14

1 Answers1

0

You are attempting to send data multiple times inside loop, hence that error. Why don't you send whole body data like below:

app.get("/api/customers", (req, res, next) =>{

    db.list({ include_docs: true }).then((body) => {
        res.send({data: body.rows});
    }).catch(e => {res.status(500).send({msg: 'Sorry, something went wrong'})});
  });

UPDATE 1

To enabled CORS, create a middleware and add it t your app

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

app.use(allowCrossDomain)
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
  • After updating the code with your answer I am getting this message in console log Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:800/api/customers. (Reason: CORS request did not succeed). – sikaili99 Sep 06 '18 at 11:46
  • I have installed cors in my express REST folder but I am still getting the error message – sikaili99 Sep 06 '18 at 11:48
  • Can you share your server-side code on how you enabled CORS? – Suresh Prajapati Sep 06 '18 at 11:57