I'm trying to make a FullStack app CRUD using ReactJs, Typescript, NodeJs, Express and MySQL. This code is having an error while i'm trying to do a post, to add a new product, returning: "TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined."
server.ts:
const express = require("express");
const cors = require("cors");
const mysql = require("mysql");
const app = express();
app.use(cors());
app.use(express.json());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "QwQvfQuFwaU$33^#gQ3oddDZ",
database: "REGPROD",
});
connection.connect((err) => {
if (err) {
console.error("Error connecting to MySQL: ", err);
} else {
console.log("Success!");
}
});
app.listen(3001, () => {
console.log("Server running on 3001");
});
// Create
app.post('/products', (req, res) => {
const { name, value, image } = req.body;
const query = "INSERT INTO products (name, value, image) VALUES (?, ?, ?)";
connection.query(query, [name, value, image], (err, result) => {
if (err) {
console.error("Error creating product: ", err);
res.status(500).send("Error creating product");
} else {
res.status(201).send("Product created successfully");
}
});
});
// Read
app.get('/products', (req, res) => {
const query = "SELECT * FROM products";
connection.query(query, (err, results) => {
if (err) {
console.error("Error fetching products: ", err);
res.status(500).send("Error fetching products");
} else {
res.status(200).json(results);
}
});
});
// Update
app.put('/products/:id', (req, res) => {
const productId = req.params.id;
const { name, value, image } = req.body;
const query = "UPDATE products SET name=?, value=?, image=? WHERE id=?";
connection.query(query, [name, value, image, productId], (err, result) => {
if (err) {
console.error("Error updating product: ", err);
res.status(500).send("Error updating product");
} else {
res.status(200).send("Product updated successfully");
}
});
});
// Delete
app.put('/products/:id', (req, res) => {
const productId = req.params.id;
const { name, value, image } = req.body;
const query = "UPDATE products SET name=?, value=?, image=? WHERE id=?";
connection.query(query, [name, value, image, productId], (err, result) => {
if (err) {
console.error("Error updating product: ", err);
res.status(500).send("Error updating product");
} else {
res.status(200).send("Product updated successfully");
}
});
});
"
Screen for adding product:
import React, { useState } from "react";
import Header from "../../components/Header";
import Form from "../../components/Form";
interface Product {
name: string;
value: number;
image?: string;
}
export default function AddProduct() {
const [products, setProducts] = useState<Product[]>([]);
const handleAddProduct = (newProduct: Product) => {
setProducts([...products, newProduct]);
};
return (
<div>
<Header />
<h1>CRUD Website</h1>
<Form AddProduct={handleAddProduct} />
</div>
);
}
Form, in that page:
import React, { useState } from "react";
interface FormProps {
AddProduct: (product: Product) => void;
}
interface Product {
name: string;
value: number;
image?: string;
}
export default function Form({ AddProduct }: FormProps) {
const [name, setName] = useState("");
const [value, setValue] = useState(0);
const [image, setImage] = useState("");
const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log(event.target.value);
setName(event.target.value);
};
const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setValue(Number(event.target.value));
};
const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setImage(event.target.value);
};
const handleSubmit = async () => {
console.log(name);
const newProduct: Product = {
name,
value,
image,
};
try {
const response = await fetch("http://localhost:3001/products", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newProduct),
});
if (response.ok) {
AddProduct(newProduct);
setName("");
setValue(0);
setImage("");
} else {
console.error("Error adding product");
}
} catch (error) {
console.error("Error adding product: ", error);
}
};
return (
<div>
<h2>Cadastrar Novo Produto</h2>
<form>
<div>
<label>Nome:</label>
<input
type="text"
value={name}
onChange={handleNameChange}
required
/>
</div>
<div>
<label>Valor:</label>
<input
type="number"
value={value}
onChange={handleValueChange}
required
/>
</div>
<div>
<label>Imagem:</label>
<input type="text" value={image} onChange={handleImageChange} />
</div>
<button type="button" onClick={handleSubmit}>
Cadastrar
</button>
</form>
</div>
);
}
what is causing this error, how to solve it?
Your express server is missing the body-parser middleware or something similar.
Add it to your server.ts then your post body will be recognized.