简体   繁体   中英

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

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

Complete code with node.js best practices.


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"));
app.use(bodyParser.urlencoded({ extended: true }));

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) {
    // here you must handle missing req.body. lets log console for now
    console.log("Name - Email missing!");
    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")
});


Use something like below

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/${newlyUser._id}`)
           }
    })
})

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