我是后端的新手,但我无法使Express Post方法正常工作。 我创建了一个名为new.ejs的文件,其中包含一个重定向到URL http://localhost:3000/campgrounds/
的表单。new.ejs文件
<% 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 %>
我查看了index.js文件,但没有发现任何问题。但是当我单击“提交”按钮时,它将重定向到http://localhost:3000/campgrounds/campgrounds
,如果http://localhost:3000/campgrounds/
index.js文件
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!');
});
我无法使此app.post正常工作。但所有其他app.get方法都可以正常工作。
答案 0 :(得分:3)
您需要在操作中添加一个斜杠。
<form action="/campgrounds" method="POST">
之所以会发生这种情况,是因为仅使用campgrounds
使其相对于您当前所在的路径(即http://localhost:3000/campgrounds
),因此它将您发送到http://localhost:3000/campgrounds/campgrounds
。