gpt4 book ai didi

javascript - Express APP如何将用户重定向到/:id path from server side

转载 作者:行者123 更新时间:2023-12-01 16:17:55 24 4
gpt4 key购买 nike

我正在学习 Node.js,我发现将用户重定向到 :id 路径时遇到了一些麻烦。我想在那里打印他的用户名。因此,为了进行概述,它是一个带有表单的登录页面,我在其中请求别名和电子邮件。当用户单击提交时,我想将他移至/:id 路径以打印其用户名。我的代码如下:

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")
})

错误如下:{ CastError: Cast to ObjectId failed for value ":id"at path "_id"for model "user"

我试过:- 将路径更改为 :_id- 添加 start/到 route

最佳答案

当您使用 redirect() 方法时,您必须传递一个真实的路由 url 而不是一个 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")
});


关于javascript - Express APP如何将用户重定向到/:id path from server side,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61558559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com