简体   繁体   中英

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

I'm doing a tutorial in the MEAN Machine book, chapter about route APIs.

Full code posted here: https://gist.github.com/leongaban/6db44e513db4ca9e784f

The following code is the API to get all users, and then to get a user by a certain id.

Get all users:

// 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);
    })
});

Follow the above is the code to get just 1 user based on id:

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

Now going to my localhost:8615/api/users/ I am able to get all the users back

I then select an id from one of the users, for example:

localhost:8615/api/users/54b64c770dedef7c1a7d2c8b

And I get the following error:

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

In my Gist you can see that my headers are set once at the top: https://gist.github.com/leongaban/6db44e513db4ca9e784f

Any idea why I'm having this problem?

You are missing the closing }) for the .get() method. So put is being called on the return of User.findById() It should be

.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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM