Hi Team
I have created a unique back end port to listen to 3001, but when i call this port on my front end for registration end point logic to listen to 3001. It gives me 404 status when inspect and it fails. What am missing and how do i fix this issue?
"<pre>registration.js:17
POST http://localhost:3000/register 500 (Internal Server Error)
registration.js:24 Registration failed:
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_BAD_RESPONSE"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 500"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: {…}, status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
stack
:
"AxiosError: Request failed with status code 500\n at settle (http:
[[Prototype]]
:
Error
"
What I have tried:
<pre>const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const app = express();
const PORT = 3000;
app.use(cors());
const username = 'ggcobani';
const password = '*****';
const database = 'cluster0';
const uri = `mongodb+srv://${username}:${password}@cluster0.dps9ft3.mongodb.net/${database}`;
mongoose.connect(uri, {
useNewUrlParser: true,
})
.then(() => {
console.log('Connected to MongoDB Atlas');
})
.catch((error) => {
console.error('MongoDB Atlas connection error:', error);
});
app.use(express.urlencoded({ extended: true }));
const User = mongoose.model('User', {
username: String,
email: String,
password: String,
});
app.post('/register', async (req, res) => {
console.log('Received registration request');
const { username, email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: 'User already exists' });
}
if (!password) {
return res.status(400).json({ message: 'Password is required' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, email, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
console.error('Registration failed:', error.message);
res.status(500).json({ message: 'Internal Server Error' });
}
});
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(401).json({ message: 'Incorrect password' });
}
res.json({ message: 'Login successful' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
import React,{useState} from "react";
import axios from "axios";
function Registration() {
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:3000/register', { username, email, password }, {
headers: {
'Content-Type': 'application/json',
},
});
console.log('User registered successfully');
} catch (error) {
console.log('Registration failed:', error);
}
};
return (
<div className="container mt-4">
<div className="card mx-auto" style={{ width: '300px', border: '2px solid black' }}>
<div className="card-body">
<h5 className="card-title text-center">Registration Form</h5>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="username">Username:</label>
<input
type="text"
className="form-control"
id="username"
placeholder="Enter your username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary btn-block">Register</button>
</form>
</div>
</div>
</div>
);
}
export default Registration;