Mobile Monitoring Solutions

Search
Close this search box.

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

MMS Founder
MMS RSS

Posted on mongodb google news. Visit mongodb google news

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 ” “

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 500n 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”

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


// 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) => {
    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 (
    
Registration Form
setUsername(e.target.value)} />
setEmail(e.target.value)} />
setPassword(e.target.value)} />
); } export default Registration;

Article originally posted on mongodb google news. Visit mongodb google news

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.