I am trying to send data from my client-side application to the server using Axios, but I am receiving an error:
AxiosError {message: ‘Request failed with status code 500’, name: ‘AxiosError’, code: ‘ERR_BAD_RESPONSE’}
When I test the same endpoint using Postman, the data is successfully passed to the database without any issues. This suggests that the server and database are functioning correctly, but there might be an issue with the client-side request.
`import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
const Signup = () => {
const [formData, setFormData] = useState({
fname: "",
lname: "",
email: "",
password: "",
userType: "customer",
});
const navigate=useNavigate()
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await axios.post(
"http://localhost:5000/api/users/register",
formData,
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(res.data);
setFormData({
fname: "",
lname: "",
email: "",
password: "",
userType: "customer",
});
if(res.status === 201){
navigate('/login');
}
} catch (error) {
console.error(error);
}
};
return (
<div className="flex items-center justify-center min-h-screen bg-gray-100">
<form
className="w-full max-w-md bg-white p-8 shadow-md rounded-md"
onSubmit={handleSubmit}
>
<h2 className="text-2xl font-bold text-center mb-6">Sign Up</h2>
<div className="mb-4">
<label
htmlFor="fname"
className="block text-gray-700 font-medium mb-1"
>
First Name
</label>
<input
type="text"
id="fname"
name="fname"
value={formData.fname}
onChange={handleChange}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
required
/>
</div>
<div className="mb-4">
<label
htmlFor="lname"
className="block text-gray-700 font-medium mb-1"
>
Last Name
</label>
<input
type="text"
id="lname"
name="lname"
value={formData.lname}
onChange={handleChange}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
required
/>
</div>
<div className="mb-4">
<label
htmlFor="email"
className="block text-gray-700 font-medium mb-1"
>
Email
</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
required
/>
</div>
<div className="mb-6">
<label
htmlFor="password"
className="block text-gray-700 font-medium mb-1"
>
Password
</label>
<input
type="password"
id="password"
name="password"
value={formData.password}
onChange={handleChange}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
required
/>
</div>
<button
type="submit"
className="w-full bg-orange-500 text-white py-2 px-4 rounded-md font-bold hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-orange-500"
>
Sign Up
</button>
</form>
</div>
);
};
export default Signup;` `const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
fname: {
type: String,
required: true,
},
lname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
userType: {
type: String,
enum: ["admin", "user"],
default: "user",
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("User", UserSchema);` `const express = require("express");
const router = express.Router();
const User = require("../../models/User");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const authenticateToken = require("../../middleware/auth");
//register
router.post("/register", async (req, res) => {
try {
const salt = await bcrypt.genSalt(10);
const password = await bcrypt.hash(req.body.password, salt);
const userobj = {
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
password: password,
userType: req?.body?.userType || "user",
};
const user = new User(userobj);
await user.save();
return res.status(201).json(user);
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
}
});
module.exports = router;` `require('dotenv').config()
const express=require('express');
const app=express();
const bodyParser=require("body-parser");
const cors=require("cors");
const connectDB=require('./config/db');
//parse requests
app.use(bodyParser.json());
app.use(express.json());
app.use(cors());
//db
connectDB();
//routes
//users route
app.use('/api/users', require('./routes/api/user'))
//task route
app.use('/api/task', require('./routes/api/task'))
const port=5000;
app.listen(port, () =>{
console.log(`Server is running on port ${port}`)
})`
2