简体   繁体   English

表单没有在发布请求中发送数据?

[英]The form is not sending data in the post request?

I am trying to get data from user and then adding it to my database.我正在尝试从用户那里获取数据,然后将其添加到我的数据库中。 But whenever i send a post request through form and try to print data in the request body it says "undefined".但是,每当我通过表单发送发布请求并尝试在请求正文中打印数据时,它都会显示“未定义”。

I tried finding answer online but it didn't help.我尝试在网上寻找答案,但没有帮助。 The error could be silly but an anyone tell me what it could be?这个错误可能很愚蠢,但有人告诉我它可能是什么?

 <form action="/products" method="POST"> <legend for="name">Name</legend> <input type="text" name="name" id="name" placeholder="Enter Product Name" required><br><br> <legend for="price">Price</legend> <input type="text" name="price" id="price" placeholder="Enter Product Price" required><br><br> <legend for="img">Image</legend> <input type="text" name="img" id="img" placeholder="Enter Product Image URL"><br><br> <legend for="img">Description</legend> <textarea name="desc" id="desc" placeholder="Enter Product Description" rows="5" cols="50"></textarea><br><br> <button type="submit">Submit</button> </form>`enter code here`


This is the main app file这是主应用程序文件

const express=require("express");
const app=express();
const mongoose=require("mongoose");
const path=require("path");
const routes=require("./routes/ec-routes");
const seed=require("./seed");

app.use(express.json())
app.set("view engine","ejs");
app.set("views",path.join(__dirname,"views"));
mongoose.connect("mongodb://localhost:27017/e-commerce")
.then(()=>console.log("DB Connected"))
.catch((err)=>console.log(err));
app.use(express.static(path.join(__dirname,"public")));
app.use(routes);
app.use(express.urlencoded({extended:false}));

//seed();
app.get("/",(req,res)=>{
    res.send("Home page");
});


app.listen(3000,(req,res)=>{
    console.log("Up At 3000")
})

This is routes file这是路由文件

const express=require("express");
const router=express.Router();
const Product=require("../models/product");


router.get("/products",async (req,res)=>{
    const products=await Product.find({});
    res.render("products/home",{products});
})
router.get("/products/new",(req,res)=>{
    res.render("products/new");
})
router.post("/products",async (req,res)=>{
    const product={
        ...req.body
    }
    console.log(req.body)
    
    res.redirect("/products");
})


module.exports=router;

Looks like you are not parsing request body.看起来您没有解析请求正文。 In order to be able to access body object in the request, you have to use a body parser.为了能够在请求中访问正文 object,您必须使用正文解析器。 Add this line to the top of your main app file将此行添加到主应用程序文件的顶部

...
app.use(express.json());
app.set("view engine","ejs");
...

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

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