I am new to backend and I am having trouble getting the express post method to work. I created a file called new.ejs which contains a form that redirects to a URL http://localhost:3000/campgrounds/
new.ejs file
<% include partials/header %>
<h1>Create a new campground</h1>
<form action="campgrounds" method="POST">
<input type="text" name='name' placeholder="name" >
<input type="text" name='image' placeholder="img-url">
<button>Submit!</button>
</form>
<% include partials/footer %>
I reviewed my index.js file and I don't see any problems whatsoever. but when I click the submit button, it redirects me to http://localhost:3000/campgrounds/campgrounds
instead if http://localhost:3000/campgrounds/
index.js file
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
let campgrounds = [
{name: "salmon creek", image: "https://pixabay.com/get/e837b1072af4003ed1584d05fb1d4e97e07ee3d21cac104491f4c278a7eeb1bc_340.jpg"},
{name: "Granite Hill", image: "https://pixabay.com/get/e83db7082af3043ed1584d05fb1d4e97e07ee3d21cac104491f4c278a7eeb1bc_340.jpg"},
{name: "Mountain Goat's Rest", image: "https://pixabay.com/get/ef3cb00b2af01c22d2524518b7444795ea76e5d004b0144591f3c079a4e9b1_340.jpg"}
]
app.get('/', (req, res) => {
res.render('landing');
});
app.get('/campgrounds', (req, res) => {
res.render("campgrounds", {campgrounds: campgrounds});
});
app.post('/campgrounds', (req, res) => {
let name = req.body.name;
let image = req.body.image;
let newCampground= {name: name, image: image}
campgrounds.push(newCampground);
res.redirect('/campgrounds')
});
app.get('/campgrounds/new', (req, res) => {
res.render('new')
});
app.listen(3000, () => {
console.log('Now serving app listening on port 3000!');
});
I cannot get this app.post to work. but all other app.get method is working fine.
You need to add a leading slash to your action.
<form action="/campgrounds" method="POST">
This happens because just using campgrounds
makes it relative to the path you're currently at, which would be http://localhost:3000/campgrounds
, and so it sends you to http://localhost:3000/campgrounds/campgrounds
.
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.