Not able to create an object while submitting form data in HTML

Viewed 35

Hello The problem was with the browser, edge was behaving differently, I am not deleting the question because someone already answered it but just in case if you faced the same issue you can try to test it in chrome.

I am trying to create an object campground with two properties title and location, I use the below shown form for that

<form action="/campgrounds" method="POST">
        <div>
            <label for="title">Title</label><br>
            <input type="text" id="title" name="campground[title]">
        </div>
        <div>
            <label for="location">Location</label><br>
            <input type="text" id="location" name="campground[location]">
        </div>
        <button>Add Campground</button>
    </form>

Below is the post route for my form.

   app.post("/campgrounds",async(req,res)=>{
      res.send(req.body);
      // const campground=new Campground(req.body.campground)
    
      // await campground.save();
    
      // res.redirect(`/campgrounds/${campground._id}`)
    })

while implementing the above code I am expecting a result like this in the route

{campground:{"title":"fdwdddsss","location":"ddhffwwscss"}}

But what I am getting is

{
  "campground{title}": "fdwdddsss",
  "campground{location}": "ddhffwwscss"
}

Can you help me understand what mistake I am doing?

1 Answers

you need to change your code to these:

<form action="/campgrounds" method="POST">
    <div>
        <label for="title">Title</label><br>
        <input type="text" id="title" name="campground[title]">
        <label for="location">Location</label><br>
        <input type="text" id="location" name="campground[location]">
    </div>
    <button>Add Campground</button>
</form>
Related