这是我的app.post
app.post("/productos", async (req, res) => {
try {
const { nombre, precio, urlImagen, categoria } = req.body;
console.log("Datos del formulario:", req.body);
const connection = await database.getConnection();
const result = await connection.query("INSERT INTO producto (nombre, precio, urlImagen, categoria) VALUES (?, ?, ?, ?)", [nombre, precio, urlImagen, categoria]);
if (result.affectedRows > 0) {
res.json({ message: "Producto agregado correctamente" });
} else {
res.status(500).json({ error: "Error al agregar el producto" });
}
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
字符串
这是我的按钮,在bootstrap中的一个模态中
<div class="modal-body">
<form action="http://localhost:4000/productos" method="post">
<!-- Campo de Producto -->
<div class="form-group">
<label for="producto">Producto</label>
<input type="text" class="form-control" id="producto" name="nombre" placeholder="Nombre del Producto" required>
</div>
<!-- Campo de Precio -->
<div class="form-group">
<label for="precio">Precio</label>
<input type="text" class="form-control" id="precio" name="precio" placeholder="Precio del Producto" required>
</div>
<!-- Campo de Imagen -->
<div class="form-group">
<label for="imagen">Imagen</label>
<input type="text" class="form-control" id="imagen" name="urlImagen" placeholder="URL de la Imagen" required>
</div>
<!-- Campo de Categoría -->
<div class="form-group">
<label for="categoria">Categoría</label>
<input type="text" class="form-control" id="categoria" name="categoria" placeholder="Categoría del Producto" required>
</div>
<!-- Botón para enviar el formulario -->
<button type="submit" class="btn btn-primary">Guardar Producto</button>
</form>
</div>
型
请求到达我的数据库,但为空
MYSQL Database request empty
我希望请求到达数据库的信息,我在表格中插入。
1条答案
按热度按时间zf2sa74q1#
正如@jQueeny所说,你必须在你的app.js中使用中间件
app.use(express.urlencoded({ extended: true} ));
,或者在你定义路由之前的任何地方。字符串
使用express.urlencoded()中间件函数从请求体中提取数据,并将其以req.body的形式添加到请求对象中