简体   繁体   中英

Automatic redirection to "/undefined" in express (nodejs)

I have been working on a code for a to do list, The issue comes when I actually go to a custom list domain and use the delete method, after deleting the method, the website automatically redirects to "localhost:3000/undefined" and the website fails to respond further, all the functionality stops except the display of the existing elements This is the node js file

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

app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/todolsDB");
const itemsSchema=new mongoose.Schema({
    toDoToday: String

});
const Item=mongoose.model("Item", itemsSchema);

const itemOne=new Item({
    toDoToday: "Wake Up"
});
const itemTwo=new Item({
    toDoToday: "Get up"
});
const itemThree=new Item({
    toDoToday: "Stand up"
});

const Items=[itemOne,itemTwo, itemThree];


const listSchema = {
    name: String,
    items: [itemsSchema]
  };
  
const List = mongoose.model("List", listSchema);



app.get("/", function(req, res){
    Item.find({}, function(err, Items){

    
    if (Items.length===0){
        Item.insertMany(Items, function(err){
            if(err){
                console.log(err)
            }
            else{
                console.log("Succesfully added!")
            }
        })
        res.redirect("/")
    }
    else{
        res.render("lists .ejs", {Day: "Today", newListItem: Items});
    }  
})});

app.get("/:topic", function(req, res){
    const topic=req.params.topic;
    List.findOne({name: topic}, function(err, results){
        if (!err){
            if (!results){
              const list = new List({
                name: topic,
                items: Items
              });
              list.save();
              res.redirect("/" + topic);
            }
            else{ 
          res.render("lists .ejs", {Day: results.name, newListItem: results.items});
            }
      }
    });
})
  




app.post("/",function(request, response){
    var itemName=request.body.newElement;
    const listName=request.body.list
  
    const item=new Item({
        toDoToday: itemName
    });
   
    if (listName==="Today"){
        response.redirect("/");
        item.save();
    }else{
        List.findOne({name:listName}, function(err, results){
            console.log(results)
            results.items.push(item)
            results.save()
            response.redirect("/"+listName);
        })
    }
    
})

=
app.post("/delete", function(req, res){
    const checkedItemId = req.body.checkbox;
    const listName = req.body.listName;
  
    if (listName === "Today") {
      Item.findByIdAndRemove(checkedItemId, function(err){
        if (!err) {
          console.log("Successfully deleted checked item.");
          res.redirect("/");
        }
      });
    } else {
      List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
        if (!err){
          res.redirect("/" + listName);
        }
      });
    }
  
  
  });
app.listen(3000, function(){
    console.log("connected to port 3000");
})

Here is the "list.ejs" file

<%-include('header.ejs')%>
    <body>
        <div class="box" id="heading">
                <h1>Today is <%= Day %></h1> 
        </div>
             <div class="box">
                    <% newListItem.forEach(function(item){ %> 
                    <form action="/delete", method="POST">
                        <div class="item">
                    
                            <input type="checkbox" name="checkbox" value="<%=item._id%>" onchange="this.form.submit()">
                            <p><%= item.toDoToday %> </p>
                    </form>
                       
                   
                </div>
                <% }) %> 
           

        
          
          <div>
                    <form action="/" method="POST" class="item">
                    <button type="submit" name="list" value=<%= Day %> >+</button>
                    <input type="text" name="newElement" placeholder="New Element" autocomplete="off">
                    <input type="hidden" name="listName" id="" value=<%= Day %> > </input>
          </div>  
        </div>
        <%-include('footer.ejs')%>
        </form>
        <script src="" async defer></script>
    </body>
</html>

On this route you have req.body.list

app.post("/",function(request, response){
    var itemName=request.body.newElement;
    const listName=request.body.list
  
    const item=new Item({
        toDoToday: itemName
    });

And on this route you have req.body.listName

app.post("/delete", function(req, res){
    const checkedItemId = req.body.checkbox;
    const listName = req.body.listName;

Most likely you are trying to access an object which does not exist, so change the property name.

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