Varun Deokar
Varun Deokar

Reputation: 21

req.params.id giving a colon before 24 digit hex code

app.post("/campsites/:id/comments", function(req, res){
Campsites.findById(req.params.id.substring(1,), function(err, campsite){
    if(err)
        console.log(err);
    else{
        console.log("Campsite found");
        Comment.create(req.body.comment, function(err, comment){
            if(err)
                console.log(err);
            else{
                console.log("Comment Created");
                campsite.comments.push(comment);
                console.log("Comment Pushed");
                campsite.save();
                console.log("Campsite Updated");
                res.redirect("/campsites/" + campsite._id);
                console.log("Redirected");
            }
        });
    }
});
});

req.params.id is returning a colon before id which is why I have to use a substring. Any idea why this is?

Upvotes: 1

Views: 319

Answers (3)

Hemanth Bathula
Hemanth Bathula

Reputation: 11

My guess is that while sending the data to url you should not include colon in that eg: route app.get("/getTrekData/:trekName") the url should be http://localhost:3000/getTrekData/Ooty it should not be http://localhost:3000/getTrekData/:Ooty

Upvotes: 1

Pardeep Baboria
Pardeep Baboria

Reputation: 468

you may should try this to accept two params from a single request.

app.post("/campsites/:id/:comments", function(req, res){

//your code

} 

and access both as req.params. parameterName If that doesn't work, try using console.log(req.params) to see what it is giving you

if you want to take the comment as body element then not need to specify it into URL, the code may be

app.post("/campsites/:id", function(req, res){

//your code

} 

and access as req. params.id and req.body.commets and make sure the value by console both.

Upvotes: 0

Adam Coster
Adam Coster

Reputation: 1462

Without seeing the code that's generating the URL leading to this endpoint, the most likely explanation is that your URL includes that colon. If you're new to Express -- the colon used in defining your routes is only used by Express's parser to indicate that that part of the URL is variable and should be named according to what comes after the colon. You replace the entire :variable-name part of a URL with the value, not just the part after the colon, for sending requests to that endpoint.

Upvotes: 1

Related Questions