Express.js路由错误:发送后不能设置头文件 [英] Express.js Routing error: Can't set headers after they are sent

查看:180
本文介绍了Express.js路由错误:发送后不能设置头文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么我会收到这个错误。这是一个基于express.js的简单API,可以添加和删除帖子。当我触发删除路由器时,会发生错误。我读过,当有两个回调通常发生错误,但是我似乎没有找到任何双重回调。

  _http_outgoing.js:344 
throw new错误('发送后不能设置头文件');
错误:发送后不能设置标题。
在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:344:11)
在ServerResponse.header(/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js :718:10)
在ServerResponse.send(/Users/bounty/Projects/_learning/react-express/node_modules/express/lib/response.js:163:12)
在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)
/ pre>

这是我的posts.js路由器:

 模块.exports = function(router){

var Post = require('../ models / post.js');

// api请求的中间件
router.use(function(req,res,next){
// do logging
console.log('something正在发生');
next(); //确保我们去我们的下一条路线,不要停在这里
});

//测试路由以确保一切正常(在GET http:// localhost:8080 / api访问)

router.get('/',function req,res){
res.json({message:'hooray!welcome to our api!'});
});

//所有路线

//路线结束于/ posts
router.route('/ posts')

//创建一个帖子(在POST http:// localhost:7777 / api / posts访问)
.post(function(req,res){
var post = new Post();
post.postTitle = req.body.postTitle; //设置帖子名称(来自请求)

//保存帖子并检查错误
post.save(function(err) {
if(err)
res.send();

res.json({message:'post created!'});
});
})

//获取所有帖子(访问GET http:// localhost:7777 / api / posts)
.get(function(req,res){
Post.find(function(err,posts){
if(err)
res.send();

res.json(posts);
});
});

//特定ID的结尾/路径的路由
router.route('/ posts /:post_id')

//获取该帖子id
.get(function(req,res){
Post.findById(req.params.post_id,function(err,post){
if(err)
res。 send(err);

res.json(post);
});
})

//用该ID更新帖子
.put(function(req,res){
Post.findById(req.params.post_id,function(err,post)){
if(err)
res.send错误);

post.postTitle = req.body.postTitle;

//保存帖子
post.save(function(err){
if(err)
res.send(err);

res.json({message:'post updated!'});
});
}) ;
})

//删除该标签的消息
.delete(function(req,res){
Post.remove({
_id:req.params.post_id
},function(err,post){
if(err){
res.send(err);
}
res.json({message:'post deleted!'});
});
});
}


解决方案

您需要添加'返回',以便您不要回复两次。

  //保存帖子并检查错误
post.save (function(err){
if(err){
return res.send();
}
res.json({message:'post created!'});
});


I'm not really sure why I'm getting this error. It's a simple API built on express.js to be able to add and remove posts. The error occurs when I trigger the delete router. I've read that the error typically happens when there are two callbacks, however, I don't seem to be able find any double callbacks.

    _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)

Here is my posts.js router:

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!' });
            });
        });
}

解决方案

You need to add the 'return' so that you don't reply twice.

// save post and check for errors
post.save(function(err) {
    if (err) {
        return res.send();
    }
    res.json({ message: 'post created!' });
});

这篇关于Express.js路由错误:发送后不能设置头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆