Error: Can't set headers after they are sent in Node / Express

Error: Can't set headers after they are sent in Node / Express

我正在做 MEAN Machine 书中的教程,关于路线的章节 APIs。

此处发布完整代码:https://gist.github.com/leongaban/6db44e513db4ca9e784f

下面的代码是API获取所有用户,然后通过某个id获取某个用户

获取所有用户:

// api/users
apiRouter.route('/users')

// create a user (accessed at POST http://localhost:8615/api/users)
.post(function(req, res) {

    // create a new instance of the User model
    var user = new User();

    // set the users information (comes from the request)
    user.name = req.body.name;
    user.username = req.body.username;
    user.password = req.body.password;

    // save the user and check for errors
    user.save(function(err) {
        if (err) {
            // duplicate entry
            if (err.code == 11000) 
                return res.json({ success: false, message: 'A user with that username already exists. '});
            else 
                return res.send(err);
        }

        // return a message
        res.json({ message: 'User created!' });
    });

})

// get all users (access at GET http://localhost:8615/api/users)
.get(function(req, res) {
    User.find(function(err, users) {
        if (err) return res.send(err);

        // return the users
        res.json(users);
    })
});

按照上面的代码根据id只获取1个用户:

// api/users/:user_id
apiRouter.route('/users/:user_id')

// get the user with that id
// (accessed at GET http://localhost:8615/api/users/:user_id)
.get(function(req, res) {
    User.findById(req.params.user_id, function(err, user) {
        if (err) return res.send(err);

        // return that user
        res.json(user);
    })

// update the user with this id
.put(function(req, res) {
    // use our user model to find the user we want
    User.findById(req.params.user_id, function (err, user) {

        if (err) return res.send(err);

        // update the users info only if its new
        if (req.body.name) user.name = req.body.name;
        if (req.body.username) user.username = req.body.username;
        if (req.body.password) user.password = req.body.password;

        // save the user
        user.save(function(err) {
            if (err) return res.send(err);

            // return a message
            res.json({ message: 'User updated!' });
        });
    })
})

// delete the user with this id
.delete(function(req, res) {
    User.remove({
        _id: req.params.user_id
    }, function(err, user) {
        if (err) return res.send(err);

        res.json({ message: 'Successfully deleted' });
        });
    });
});

现在转到我的 localhost:8615/api/users/ 我可以恢复所有用户

然后我 select 来自其中一位用户的 ID,例如:

localhost:8615/api/users/54b64c770dedef7c1a7d2c8b

我收到以下错误:

TypeError: Object #<Query> has no method 'put'
at adminRouter.param.req.name (/Users/leongaban/NodeDallas/projects/awesome-  test/server.js:110:3)
at Layer.handle [as handle_request] (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/layer.js:82:5)
at next (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/layer.js:82:5)
at /Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/index.js:233:24
at param (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/index.js:330:14)
at param (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/index.js:346:14)
at Function.proto.process_params (/Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/index.js:390:3)
at /Users/leongaban/NodeDallas/projects/awesome-test/node_modules/express/lib/router/index.js:227:12

在我的 Gist 中你可以看到我的 headers 在顶部设置了一次: https://gist.github.com/leongaban/6db44e513db4ca9e784f

知道我为什么会遇到这个问题吗?

您缺少 .get() 方法的结尾 })。所以在 User.findById() 的 return 上调用 put 应该是

.get(function(req, res) {
    User.findById(req.params.user_id, function(err, user) {
        if (err) return res.send(err);

        // return that user
        res.json(user);
    })
}) // <-- was missing
// update the user with this id
.put(function(req, res) {