I don’t know what happens. When I save the form no error appears, but the form is not saved in the database. I’ve been trying for a while to see if it’s the connection, the names, errors in the code, but I can’t find a solution.
Can someone help me see what my error is? even though according to the form there is no problem saving it, this is not reflected in the database.
This is my Create.jsx document
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';
import { Link } from 'react-router-dom';
function Create() {
const [values, setValues] = useState({
name: '',
email: '',
age: '',
gender: ''
});
const [message, setMessage] = useState('');
const [isError, setIsError] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setValues(prevValues => ({ ...prevValues, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
axios.post('http://localhost:5000/add_user', values)
.then((res) => {
setMessage('Estudiante agregado con éxito');
setIsError(false);
setValues({
name: '',
email: '',
age: '',
gender: ''
});
})
.catch((err) => {
setMessage('Error al agregar el estudiante: ' + err.message);
setIsError(true);
});
};
return (
<div className='container vh-100 d-flex justify-content-center align-items-center'>
<div className='col-md-8 col-lg-6'>
<div className='card'>
<div className='card-header bg-primary text-white'>
<h4 className='mb-0'>Añadir Estudiante</h4>
</div>
<div className='card-body'>
<form onSubmit={handleSubmit}>
{message && (
<div className={`alert ${isError ? 'alert-danger' : 'alert-success'}`} role='alert'>
{message}
</div>
)}
<div className='mb-3'>
<label htmlFor='name' className='form-label'>Nombre</label>
<input
type='text'
name='name'
id='name'
className='form-control'
required
value={values.name}
onChange={handleChange}
/>
</div>
<div className='mb-3'>
<label htmlFor='email' className='form-label'>Correo Electrónico</label>
<input
type='email'
name='email'
id='email'
className='form-control'
required
value={values.email}
onChange={handleChange}
/>
</div>
<div className='mb-3'>
<label htmlFor='age' className='form-label'>Edad</label>
<input
type='number'
name='age'
id='age'
className='form-control'
required
value={values.age}
onChange={handleChange}
/>
</div>
<div className='mb-3'>
<label htmlFor='gender' className='form-label'>Género</label>
<select
name='gender'
id='gender'
className='form-select'
required
value={values.gender}
onChange={handleChange}
>
<option value=''>Selecciona tu género</option>
<option value='male'>Masculino</option>
<option value='female'>Femenino</option>
<option value='other'>Otro</option>
</select>
</div>
<div className='d-flex justify-content-between'>
<button type='submit' className='btn btn-success'>Guardar</button>
<Link to='/' className='btn btn-secondary'>Regresar</Link>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
export default Create;
This is my App.js document
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import "bootstrap/dist/css/bootstrap.min.css";
import './App.css';
import Create from './components/Create';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/create" element={<Create />} />
</Routes>
</BrowserRouter>
);
}
export default App;
This is my server.js document
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const path = require("path");
const app = express();
//path.resolve()
app.use(express.static(path.join(__dirname, "public")));
app.use(cors());
app.use(express.json());
const port = 5000;
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "students",
});
app.listen(port, () => {
console.log(`listening`);
});
app.post("/add_user", (req, res) => {
const sql =
"INSERT INTO student_details (`name`,`email`,`age`,`gender`) VALUES (?, ?, ?, ?)";
const values = [req.body.name, req.body.email, req.body.age, req.body.gender];
db.query(sql, values, (err, result) => {
if (err)
return res.json({ message: "Something unexpected has occured" + err });
return res.json({ success: "Student added successfully" });
});
});