Express JS/HTML 表单提交问题

问题描述 投票:0回答:1

我正在尝试向 Express JS 服务器提交表单,但我没有在后端获取任何表单数据。

这是我的 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>

这里是express JS应用程序

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!');
});

当我尝试打印

id
params
的值时,我总是无法定义。 这段代码中我缺少什么?

HTML 文件放置在公共文件夹中,如下所示

index.html

javascript html express
1个回答
0
投票

在后端添加此方法来加载index.html页面后,它就起作用了。

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});
© www.soinside.com 2019 - 2024. All rights reserved.