javascript - Node.js JSON headers -


i'm toying node.js server-app has routes both homemade rest api , serving static pages. when serves static pages no errors, when serves stuff api, following in console:

error: can't set headers after sent. @ sendstream.headersalreadysent (c:\path_to_node_folder\node_modules\send\lib\send.js:302:13) @ sendstream.send (c:\path_to_node_folder\node_modules\express\node_modules\send\lib\send.js:490:17) @ c:\path_to_node_folder\node_modules\express\node_modules\send\lib\send.js:467:10 @ fsreqwrap.oncomplete (fs.js:82:15) 

my routes:

module.exports = function(app) {    "use strict";      app.get('/api', function(req, res, next) {      res.json({        message : 'welcome angular blog restful api'      });      next();    });      app.get('/api/article/:permalink', function(req, res, next) {      res.json({        message   : "article retrieved",        permalink : req.params.permalink      });      next();    });      app.post('/api/comment', function(req, res, next) {      res.json({        message : "save comment"      });      next();    });      app.use(function(req, res) {      // use res.sendfile, streams instead of reading file memory.      res.sendfile('./public_html/index.html');    });  };

now, please don't hate on returned json data, messing around :)

question: how rid of above console-error?

you can call either res.json() or next(), not both. call next() if implementing middleware or if want forward error error handler.

if (!req.query.userid) {   return next(new error('userid missing!')); } res.json({ message: "ok" }); 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -