首页 文章

ejs表单重定向到URL的双重副本(express.js)

提问于
浏览
0

我是后期新手,我无法使用快速发布方法 . 我创建了一个名为new.ejs的文件,其中包含一个重定向到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 %>

我查看了我的index.js文件,但我没有看到任何问题 . 但当我点击提交按钮时,如果 http://localhost:3000/campgrounds/ ,它会将我重定向到 http://localhost:3000/campgrounds/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!');
});

我无法得到这个app.post工作 . 但所有其他app.get方法工作正常 .

1 回答

  • 3

    您需要为操作添加前导斜杠 .

    <form action="/campgrounds" method="POST">
    

    发生这种情况是因为只使用 campgrounds 使其相对于您当前所在的路径,即 http://localhost:3000/campgrounds ,因此它会将您发送到 http://localhost:3000/campgrounds/campgrounds .

相关问题