How does ports in the server on react connect to the ports in front end for database to store values?

Hi Team

I have a server js file that connects to the database and i am using mongodb, the issue is on the ports they dont seem to communicate to the server. Meaning when i click register button from the front end. I get 404 status. Here is an error

 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, …}
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
"Request failed with status code 500"
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
{data: {…}, status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
"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)"


// back end server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

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

// Enable CORS

// Connect to MongoDB Atlas
const username = 'ggcobani';
const password = '*****';
const database = 'cluster0';

const uri = `mongodb+srv://${username}:${password}${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,
});'/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

        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'/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, 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}`);


// front end
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) => {

    try {
        await'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>
                placeholder="Enter your username"
                onChange={(e) => setUsername(}
            <div className="form-group">
              <label htmlFor="email">Email:</label>
                placeholder="Enter your email"
                onChange={(e) => setEmail(}
            <div className="form-group">
              <label htmlFor="password">Password:</label>
                placeholder="Enter your password"
                onChange={(e) => setPassword(}
            <button type="submit" className="btn btn-primary btn-block">Register</button>
export default Registration;

well im guessing the server isnt listening for database connections on port 80…

Must my cloud database on mongodb be 27017 or, then server should be same as this and front end? Please advice

Well only your database host can tell you for sure what port you’re supposed to be using in the URL string, but every example I can find (and that collection of links includes MongoDB and Mongoose’s own pages…) has 27017 in the connection URL string…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.