简体   繁体   English

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

[英]ejs form redirects to double copy of URL(express.js)

I am new to backend and I am having trouble getting the express post method to work. 我是后端的新手,因此无法使用Express Post方法。 I created a file called new.ejs which contains a form that redirects to a URL http://localhost:3000/campgrounds/ 我创建了一个名为new.ejs的文件,其中包含一个重定向到URL http:// localhost:3000 / campgrounds /的表单。

new.ejs file 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 %>

I reviewed my index.js file and I don't see any problems whatsoever. 我查看了index.js文件,但没有发现任何问题。 but when I click the submit button, it redirects me to http://localhost:3000/campgrounds/campgrounds instead if http://localhost:3000/campgrounds/ 但是当我单击“提交”按钮时,它将重定向到http://localhost:3000/campgrounds/campgrounds而不是http://localhost:3000/campgrounds/

index.js file 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!');
});

I cannot get this app.post to work. 我无法使此app.post正常工作。 but all other app.get method is working fine. 但所有其他app.get方法都可以正常工作。

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 . 发生这种情况是因为仅使用campgrounds使其相对于您当前所在的路径(即http://localhost:3000/campgrounds ,因此会将您发送到http://localhost:3000/campgrounds/campgrounds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM