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
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) => {
});
If you recieve the same error you can add "/" to today like "/today/" or try to change the type submit to button
You need to set your view engine to use ejs and use the
bodyParser.json()
function to extract the parsedreq.body
like so:Make sure you have a folder named
views
with yourindex.ejs
inside of it because theres.render()
method will look in aviews
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.