Express server is returning an HTML page when the registration form is expecting a JSON response

When attempting to register a user to the database I am hit with

Register.jsx:54 Registration error: SyntaxError: Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON.

I am using express as the server-side with mongoDB and react as the front end. I assume it has to do with the pathing but I am at a loss on where the issue might be.

My App.jsx:

// IMPORTS HERE
import './App.css'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import WelcomeMessage from './components/WelcomeMessage'
import SortFilterMenu from './components/SortFilterMenu'
import Login from '../src/pages/Login';
import Register from '../src/pages/Register';
// import FetchAndDisplayFromQueue from './FetchAndDisplayFromQueue';


function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<><WelcomeMessage/><SortFilterMenu/></>} />
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        {/* More routes can be added here */}
      </Routes>
    </Router>
  );
}

export default App

Register.jsx goes as follows:

import { useState } from 'react';

function Register() {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const handleRegister = async (e) => {
    e.preventDefault();

    if (password !== confirmPassword) {
      console.error("Passwords don't match.");
      return;
    }

    const registerData = {
      username: username,
      email: email,
      password: password,
    };

    try {
      const response = await fetch('/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(registerData),
        credentials: 'include', // Needed for cookies
      });

      if (response.ok) {
        console.log("Registration successful");
        window.location.href = '/login';
      } else {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to register');
      }
    } catch (error) {
      console.error('Registration error:', error);
    }
  };

  return (
    <div className="container d-flex justify-content-center align-items-center min-vh-100">
      <div className="row border rounded-5 p-4 bg-white shadow box-area">
        <div className="col-md-6 rounded-4 d-flex justify-content-center align-items-center flex-column left-box" style={{ background: '#00011a'}}>
        <div className="featured-image mb-3">
            <img src="/logo.png" className="img-fluid" alt="logo" style={{ width: '250px' }} />
          </div>
          <p className="text-white fs-2" style={{ fontFamily: "'Courier New', Courier, monospace", fontWeight: 600 }}>Welcome Back!</p>
        </div>
        <div className="col-md-6 right-box">
          <form onSubmit={handleRegister}>
          
            <div className="header-text mb-4">
              <h2>CinemaWorld</h2>
            </div>
            <div className="input-group mb-3" style={{ marginLeft: '15px' }}>
                <input 
                  name="username" 
                  type="text" 
                  className="form-control form-control-lg bg-light fs-6" 
                  placeholder="Username" 
                  required 
                  value={username} 
                  onChange={e => setUsername(e.target.value)} 
                />
              </div>
            <div className="input-group mb-3" style={{ marginLeft: '15px' }}>
                <input 
                  name="email" 
                  type="email" 
                  className="form-control form-control-lg bg-light fs-6" 
                  placeholder="Email address" 
                  required 
                  value={email} 
                  onChange={e => setEmail(e.target.value)} 
                />
              </div>
              <div className="input-group mb-3" style={{ marginLeft: '15px' }}>
                <input 
                  name="password" 
                  type="password" 
                  className="form-control form-control-lg bg-light fs-6" 
                  placeholder="Password" 
                  required 
                  value={password} 
                  onChange={e => setPassword(e.target.value)} 
                />
              </div>
            <div className="input-group mb-3" style={{ marginLeft: '15px' }}>
              <input 
                name="confirmPassword" 
                type="password" 
                className="form-control form-control-lg bg-light fs-6" 
                placeholder="Confirm Password" 
                required 
                value={confirmPassword} 
                onChange={e => setConfirmPassword(e.target.value)} 
              />
            </div>
            {/* Rest of your form content */}
            <div className="input-group mb-3" style={{ marginLeft: '15px' }}>
              <button type="submit" className="btn btn-lg btn-primary w-100 fs-6">Register</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

export default Register;

The route setup in my route.js:

router.post('/register', async (req, res, next) => {
  try {
    
    const { username, email, password } = req.body;

    // Create a new User instance with the extracted fields
    const newUser = new User({ username, email, password });

   
    await newUser.save();

    // Redirect to login on successful registration
    res.redirect('/login');
  } catch (error) {
    // Check for a MongoDB duplicate key
    if (error.code === 11000) {
      return res.status(400).json({ error: "Email or username already exists." });

    }
    
    // Log the full error for debugging purposes
    console.error('Registration error:', error);

    // Send a generic error response
    return res.status(400).json({error:"An error occurred during registration."});
  }
});

My server.js used to run the backend:

require('dotenv').config();
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const cors = require('cors');
const passport = require('passport');
const bodyParser = require('body-parser');
const path = require('path');
const flash = require('connect-flash');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const app = express();

// Import routes
const userRoutes = require('./routes/route');
const apiRoutes = require('./routes/api');

app.use(helmet()); // Set security-related HTTP headers
app.use(rateLimit({ // Basic rate-limiting middleware
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // Limit each IP to 100 requests per windowMs
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: process.env.SECRET_KEY,
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false, httpOnly: true }
}));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(flash());

const authMiddleware = require('./middleware/authentication');
app.use(authMiddleware.initialize());
app.use(authMiddleware.session());

// Connect to MongoDB
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI);
    console.log('Connected to MongoDB');
  } catch (err) {
    console.error('Failed to connect to MongoDB', err);
    process.exit(1); // Exit process with failure
  }
};

connectDB();

// Error handling middleware
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  console.error(err);
  if (process.env.NODE_ENV === 'development') {
    res.status(statusCode).json({ error: err.message, stack: err.stack });
  } else {
    res.status(statusCode).json({ error: 'Internal Server Error' });
  }
});

app.use((error, req, res, next) => {
  res.status(error.status || 500).json({
    error: {
      message: error.message || 'An unknown error occurred.',
    },
  });
});

// Use routes
app.use('/', userRoutes);
app.use('/', apiRoutes);

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`)).on('error', (err) => {
  console.error('Failed to start server:', err);
});

Expected user to be added to database, currently does not work.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật