POST Error when making a move on a chess board

I have a frontend chess board where each piece is movable/draggable to a square and the moves are to be transferred over to the backend via the post api.

FRONTEND:

<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chess Board</title>
  <style>
    #chessboard {
      width: 400px;
      height: 400px;
      display: flex;
      flex-wrap: wrap;
    }

    .square {
      width: 50px;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer; 
    }

    .black {
      background-color: #769656;
    }

    .white {
      background-color: #eeeed2;
    }

    .piece {
      font-size: 40px;
      cursor: move; 
      user-select: none;
      -webkit-user-drag: none; 
    }
  </style>
</head>
<body>
  <div id="chessboard"></div>

  <script>
    document.addEventListener("DOMContentLoaded", function() {
      const chessboard = document.getElementById("chessboard");
      let draggedPiece = null;
      let prevRow, prevCol;

      // Function to generate chessboard
      function generateChessboard() {
        const piecesOrder = ['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'];
        const pawns = '♟'.repeat(8);

        for (let row = 0; row < 8; row++) {
          for (let col = 0; col < 8; col++) {
            const square = document.createElement("div");
            square.classList.add("square");
            square.id = `square-${row}-${col}`; // Assign unique id to each square
            if ((row + col) % 2 === 0) {
              square.classList.add("white");
            } else {
              square.classList.add("black");
            }
            square.dataset.row = row;
            square.dataset.col = col;

            const piece = document.createElement("span");
            piece.classList.add("piece");

            // Set up initial positions for white and black pieces
            if (row === 0) {
              piece.textContent = piecesOrder[col];
            } else if (row === 1) {
              piece.textContent = pawns[col];
            } else if (row === 6) {
              piece.textContent = pawns[col].toUpperCase(); // Capitalize for black pawns
            } else if (row === 7) {
              piece.textContent = piecesOrder[col].toUpperCase(); // Capitalize for black pieces
            }

            piece.draggable = true; // Make pieces draggable

            piece.addEventListener("dragstart", dragStart); // Add dragstart event listener

            square.appendChild(piece);
            chessboard.appendChild(square);
          }
        }
      }

      // Drag-and-drop functions
      function dragStart(event) {
        draggedPiece = event.target;
        prevRow = draggedPiece.parentElement.dataset.row;
        prevCol = draggedPiece.parentElement.dataset.col;
        event.dataTransfer.setData("text/plain", ""); 
      }

      chessboard.addEventListener("dragover", dragOver); 
      chessboard.addEventListener("drop", drop); 

      function dragOver(event) {
        event.preventDefault();
      }

      function drop(event) {
    event.preventDefault();
    const targetSquare = event.target.closest(".square");
    const targetPiece = targetSquare.querySelector(".piece");
    if (!targetPiece) {
        targetSquare.appendChild(draggedPiece);
        draggedPiece = null;
    } else {
        const sourceSquare = draggedPiece.parentElement;
        const fromSquare = sourceSquare.id; 
        const toSquare = targetSquare.id;
        makeMove(fromSquare, toSquare); 
        targetSquare.removeChild(targetPiece);
        targetSquare.appendChild(draggedPiece);
        sourceSquare.appendChild(targetPiece);
    }
    const newRow = targetSquare.dataset.row;
    const newCol = targetSquare.dataset.col;
    console.log(`Piece moved from (${prevRow},${prevCol}) to (${newRow},${newCol})`);
}


      // Generate the chessboard
      generateChessboard();
    });


    // Function to make a move on the chessboard via the backend server
function makeMove(fromSquare, toSquare) {
    fetch('/move', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ fromSquare, toSquare })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
  
        console.error('Error:', error);
    });
}
  </script>

BACKEND:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use((req, res, next) => {
    // Allow requests from any origin
    res.setHeader('Access-Control-Allow-Origin', '*');
    // Allow certain HTTP methods
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    // Allow certain HTTP headers
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    // Allow credentials (if needed)
    res.setHeader('Access-Control-Allow-Credentials', true);
    
    // Move to the next middleware
    next();
  });
app.use(express.static('public'));
app.use(bodyParser.json());
let port=2000;
app.listen(port, () => {
    console.log("Listening on port ${port}");
});

// Function to initialize the chessboard with starting positions
function initializeChessboard() {
    return [
        [5, 3, 4, 6, 7, 4, 3, 5], // Black pieces in the first row
        [1, 1, 1, 1, 1, 1, 1, 1], // Black pawns in the second row
        Array(8).fill(0), 
        Array(8).fill(0),
        Array(8).fill(0),
        Array(8).fill(0),
        [11, 11, 11, 11, 11, 11, 11, 11], // White pawns in the second-to-last row
        [15, 13, 14, 16, 17, 14, 13, 15] // White pieces in the last row
    ];
}

// Array to store the current state of the chessboard
let chessboardState = initializeChessboard();

// Route to get the current state of the chessboard
app.get('/chessboard', (req, res) => {
    res.json(chessboardState);
});

// Route to make a move on the chessboard
app.post('/move', (req, res) => {
    const { fromSquare, toSquare } = req.body;

    // Parse the coordinates of the squares
    const [fromRow, fromCol] = parseCoordinates(fromSquare);
    const [toRow, toCol] = parseCoordinates(toSquare);

    // Check if the move is valid
    if (!isValidMove(fromRow, fromCol, toRow, toCol)) {
        return res.status(400).json({ status: 'error', message: 'Invalid move' });
    }

    // Make the move on the chessboard
    chessboardState[toRow][toCol] = chessboardState[fromRow][fromCol];
    chessboardState[fromRow][fromCol] = 0; // Clear the source square

    // Send a response indicating the move was successful
    res.json({ status: 'success', message: 'Move processed successfully' });
});

// Function to parse coordinates from square notation (e.g., 'a1' to [0, 0])
function parseCoordinates(square) {
    const col = square.charCodeAt(0) - 'a'.charCodeAt(0);
    const row = 8 - parseInt(square[1]);
    return [row, col];
}

// Function to check if a move is valid
function isValidMove(fromRow, fromCol, toRow, toCol) {
    return true;
}

Whenever I run the program and check the DEVTOOLS on the frontend side, the post api never seems to work when I make a move on the chessboard. I keep getting the 500 status code error.

New contributor

ADIT K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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