我不太确定为什么会收到此错误。这是一个基于express.js的简单API,能够添加和删除帖子。当我触发删除路由器时发生错误。我读到错误通常在有两个回调的情况下发生,但是,我似乎找不到任何双重回调。
_http_outgoing.js:344 throw new Error('Can\'t set headers after they are sent.'); Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at ServerResponse.header (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:718:10) at ServerResponse.send (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:163:12) at ServerResponse.json (/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:249:15) at /Users/bounty/Projects/_learning/react-express/server/routes/posts.js:86:9 at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13)
这是我的posts.js路由器:
module.exports = function(router) { var Post = require('../models/post.js'); // middleware for the api requests router.use(function(req, res, next) { // do logging console.log('something is happening.'); next(); // make sure we go to our next route and don't stop here }); // test route to make sure everything is working (accessed at GET http://localhost:8080/api) router.get('/', function(req, res) { res.json({ message: 'hooray! welcome to our api!' }); }); // all routes here // routes that end in /posts router.route('/posts') // create a Post (accessed at POST http://localhost:7777/api/posts) .post(function(req, res) { var post = new Post(); post.postTitle = req.body.postTitle; // set the post name (comes from request) // save post and check for errors post.save(function(err) { if (err) res.send(); res.json({ message: 'post created!' }); }); }) // get all Posts (accessed at GET http://localhost:7777/api/posts) .get(function(req, res) { Post.find(function(err, posts) { if (err) res.send(); res.json(posts); }); }); // routes that end in /posts for specific id router.route('/posts/:post_id') // get the post with that id .get(function(req, res) { Post.findById(req.params.post_id, function(err, post) { if (err) res.send(err); res.json(post); }); }) // update the post with that id .put(function(req, res) { Post.findById(req.params.post_id, function(err, post) { if (err) res.send(err); post.postTitle = req.body.postTitle; // save the post post.save(function(err) { if (err) res.send(err); res.json({ message: 'post updated!' }); }); }); }) // deletes the post with that id .delete(function(req, res) { Post.remove({ _id: req.params.post_id }, function(err, post) { if (err) { res.send(err); } res.json({ message: 'post deleted!' }); }); }); }
您需要添加“返回”,这样您就不会再次回答。
// save post and check for errors post.save(function(err) { if (err) { return res.send(); } res.json({ message: 'post created!' }); });