Quick Background
I have a React component called ‘Register.jsx’ that allows users to create a username and password. The submit button sends the information to the Express backend and a row is created in a MySQL table that stores the usernames and passwords. In MySQL, I have the ‘username’ column set to unique values only and an error for duplicate entries is generated in Express…
{
"message": "ER_DUP_ENTRY"
}
Desired Results
I would like to display that error in the ‘Register.jsx’ component and allow them to retry it.
Current Results
I can’t seem to be able to retrieve the error message. When I hit the endpoint on Postman, I get the response, so I know the Express portion works.
Relevant Code
Register.jsx
const handleSubmit = async () => {
try {
const res = await createUser(username, password);
console.log(res)
} catch (err) {
console.log(err);
setError(JSON.stringify(err))
}
}
createUser.js
try {
const response = await fetch('http://localhost:3001/register', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
}
})
} catch (error) {
return error;
}
index.js
app.post('/register', async (req, res) => {
const data = req.body;
const username = data.username;
const password = data.password;
const query = `INSERT INTO accounts (username, password, email) VALUES ('${username}','${password}');`;
try {
const result = await connection.query(query);
const res = JSON.stringify(result)
res.status(200).send({ message: 'success'})
} catch (error) {
return res.status(401).send({ message: error.code});
}
})
What I’ve Tried
I’ve tried all combination of JSON.stringify/return/console.log the caught & sent errors. I’ve tried to debug with console.log(error) to see what’s going on. I’ve made no progress in 3 – 5 hours. I’ve tried using State hooks also, but since my console.logs are blank it doesn’t really matter.


