Skip to content
Advertisement

Express APP how to redirect user to /:id path from server side

I’m learning Node.js and I’m finding some troubles with redirecting the user to an :id path. I would like to print there his username. So to make an overview it is a landing page with a form where I ask for an Alias and an email. When user clicks submit I’d like to move him to /:id path to print its’ username. My code is the following:

var express  = require("express"),
    app      = express(),
    request  = require("request"),
    mongoose = require("mongoose"),
    bodyParser = require("body-parser");

app.set("view engine", "ejs")
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));

mongoose.connect("mongodb://localhost/Scape_Room", {useNewUrlParser: true, useUnifiedTopology: true});
var userSchema = new mongoose.Schema({
    email: String,
    alias: String,
});

var user = mongoose.model ("user",userSchema);

app.get("/", function(req, res){
    res.render("index")
})

app.post("/newuser", function(req,res){
    var name = req.body.name;
    var email = req.body.email;
    var newUser = {name:name, email:email}
    user.create(newUser, function(err,newlyUser){
        if(err){
           console.log(err)
           } else {
               res.redirect("/start/:id")
           }
    })
})

app.get("/start/:id", function(req,res){
    user.findById(req.params.id, function(err, foundUser){
        if(err){
            console.log(err)
        } else{
            res.render("startPoint", {user:foundUser})
        }
    })
})

app.listen(3000, function(err){
        console.log("Server listening")
})

error is the following: { CastError: Cast to ObjectId failed for value “:id” at path “_id” for model “user”

I’ve tried: – to change the path to :_id – added start/ into the route

Advertisement

Answer

When you are using the redirect() method, you must pass a real route url not an id.

const express = require("express")
const request = require("request");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();

app.set("view engine", "ejs")
app.use(express.static("public"));

mongoose.connect("mongodb://localhost/Scape_Room", { useNewUrlParser: true, useUnifiedTopology: true });

const userSchema = new mongoose.Schema({
  email: String,
  alias: String,
});

const user = mongoose.model("user", userSchema);

app.get("/", function (req, res) {
  res.render("index");
});

app.post("/newuser", function (req, res) {
  const { name, email } = req.body;
  if (!name || !email) {
    return res.end();
  }

  const newUser = { name: name, email: email }
  user.create(newUser, function (err, newlyUser) {
    if (err) {
      console.log(err);
      return res.end();
    }

    if (!newlyUser) {
      console.log("Couldn't save user!");
      return res.end();
    }

    if (!newlyUser.id) {
      console.log("No user id found");
      return res.end();
    }

    res.redirect(`/start/${newlyUser.id}`);
  });
});

app.get("/start/:id", function (req, res) {
  user.findById(req.params.id, function (err, user) {
    if (err) {
      console.log(err);
    } else {
      res.render("startPoint", { user });
    }
  })
})

app.listen(3000, function (err) {
  console.log("Server listening")
});


Advertisement