October 24, 2024
Chicago 12, Melborne City, USA
HTML

Express JS/HTML Form Submission Issue


I am trying to submit a form to an express js server but I am not getting any form data on the backend.

Here is my HTML.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Uploader</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            display: flex;
            justify-content: space-between;
        }
        .column {
            width: 45%;
        }
        #response1, #response2 {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
    <script>
        async function submitForm(event) {
            event.preventDefault();
            const formData = new FormData(document.getElementById('form'));
            try {
                const response = await fetch('/submit', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('Failed to submit Form 1');
                }

                const result = await response.json();
                document.getElementById('response').innerText = result.message;
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('response').innerText="Error: " + error.message;
            }
        }
    </script>
</head>
<body>

<div class="column">
    <h2>Form 1</h2>
    <form id="form" onsubmit="submitForm(event)">
        <label for="id">Id:</label><br>
        <input type="text" id="id" name="id" required><br><br>
        <label for="filename">File Name:</label><br>
        <input type="text" id="filename" name="filename" required><br><br>
        <label for="filepath">File Path:</label><br>
        <input type="text" id="filepath" name="filepath" required><br><br>
        <button type="submit">Submit</button>
    </form>
    
    <div id="response"></div>
</div>

</body>
</html>

Here is the express JS app

import { ExtService } from "./extService";
var express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors')

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors());
app.use(express.json())

const PORT = 3000;

app.post('/submit', async (req, res) => {
  const { id, filename, filepath } = req.body;

  console.log(id);
  const params = req.body;
  console.log(params);
  console.log('id: '+ params.id);

  const extService = new ExtService();
  const response = await extService.create(id, filename, filepath);

  res.send(response);
});

app.listen(PORT, function () {
  console.log('Example app listening on port 3000!');
});

I always get undefind when I am trying to print the values of id or params.
What am I missing in this code?

The HTML file is placed inside public folder as index.html.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video