skip to Main Content

I’m trying to name the route in an app.post() (for example: app.post("/today")), but every time that I do it, the server gives an error:

cannot submit / Post.

Please help me what I should do to fix it.

index.js

import express from "express";
import bodyParser from "body-parser";
const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

let taskList = [];
let viewTaskList = ["Task 1","Task 2","Task 3","Task 4"];

app.get("/", (req, res) => {
    
    res.render("index.ejs", {
        views: viewTaskList
    });  

});

app.post("/today", (req, res) => {
    
    let itemName = req.body.task;
    let button = req.body.add;
    button = true;
    if (button) {
        taskList.push(itemName);   
    }

    res.render("index.ejs", {
        task: taskList,
        views: viewTaskList
    }); 

});


app.listen(port, () => {
    console.log(`Listening on port ${port}`);
  });

index.ejs:

<form action="/today" method="post">
    <input type="text" name="task" placeholder="New Item">
    <button type="submit" value="Add">+</button>
</form>

2

Answers


  1. try comment everything inside the post request and try to show req.body maybe you are not putting the correct data. If you don’t see any wrong maybe it is the values you are trying to post as itemName and button.

    app.post("/today", (req, res) => {

    console.log("body", req.body)
    
    // let itemName = req.body.task;
    //let button = req.body.add;
    //button = true;
    //if (button) {
        //taskList.push(itemName);   
    //}
    
    //res.render("index.ejs", {
        //task: taskList,
        //views: viewTaskList
    //}); 
    

    });

    If you recieve the same error you can add "/" to today like "/today/" or try to change the type submit to button

    Login or Signup to reply.
  2. You need to set your view engine to use ejs and use the bodyParser.json() function to extract the parsed req.body like so:

    import express from "express";
    import bodyParser from "body-parser";
    const app = express();
    const port = 3000;
    app.set('view engine', 'ejs'); //< Add this
    app.use(bodyParser.json()); //< And this
    
    //...Rest of your code 
    

    Make sure you have a folder named views with your index.ejs inside of it because the res.render() method will look in a views folder for the view.

    Lastly, make sure you restart your index.js or better yet, use something like nodemon, pm2 or forever to watch for file changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search