[英]ejs form redirects to double copy of URL(express.js)
我是后端的新手,因此無法使用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方法都可以正常工作。
您需要在操作中添加一個斜杠。
<form action="/campgrounds" method="POST">
發生這種情況是因為僅使用campgrounds
使其相對於您當前所在的路徑(即http://localhost:3000/campgrounds
,因此會將您發送到http://localhost:3000/campgrounds/campgrounds
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.