Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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?

JavaScript
"<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://localhost:3001/static/js/bundle.js:50189:12)\n    at XMLHttpRequest.onloadend (http://localhost:3001/static/js/bundle.js:48871:66)"
[[Prototype]]
: 
Error
"

What I have tried:

JavaScript
<pre>const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const app = express();
const PORT = 3000;

// Enable CORS
app.use(cors());



// Connect to MongoDB Atlas
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);
  });

// Middleware to parse JSON in the request body
app.use(express.urlencoded({ extended: true }));

// User model
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 {
        // Check if user already exists
        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' });
        }

        // Hash the password
        const hashedPassword = await bcrypt.hash(password, 10);

        // Create a new user
        const newUser = new User({ username, email, password: hashedPassword });

        // Save the new user
        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' });
    }
});

// Login endpoint
app.post('/login', async (req, res) => {
  const { email, password } = req.body;

  // Find the user by email
  const user = await User.findOne({ email });

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  // Compare passwords
  const passwordMatch = await bcrypt.compare(password, user.password);

  if (!passwordMatch) {
    return res.status(401).json({ message: 'Incorrect password' });
  }

  res.json({ message: 'Login successful' });
});


// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});



import React,{useState} from "react";
import axios from "axios";


// registration function
function Registration() {
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    
    
    // handling of submit button during registration
    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 submit from the form.
 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;
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900