Nodejs 表单数据上传如何阻止页面跳转

Nodejs 表单数据上传如何阻止页面跳转

我 在客户端用 <form action="/userInfo" method=“post” name=“basicInfo”> 然后 服务器端用 app.post(’/userInfo’,routes.userInfo); 这个来处理。 处理函数: exports.userInfo = function(req,res) { var info = {}; info.age = req.body.age; //get form data from client info.sex = req.body.sex; info.weight = req.body.weight; info.height = req.body.height; info.email = req.body.email; info.password = req.body.password;

mogodb.info = info;

console.log(info);
console.log(req.query);
res.end();

};

现在问题是,上传完成之后页面会发生跳转,而我的功能只是上传下数据而已,不希望跳转,我应该怎么做呢?


11 回复

要在 Node.js 中处理表单数据上传而不导致页面跳转,可以使用 AJAX 技术(如 Fetch API 或 XMLHttpRequest)来异步提交表单数据。以下是详细的步骤和示例代码:

客户端代码

首先,修改你的 HTML 表单以禁用默认的提交行为,并使用 JavaScript 来发送 AJAX 请求。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Data Upload Example</title>
</head>
<body>
    <form id="basicInfo" action="/userInfo" method="POST">
        <label for="age">Age:</label>
        <input type="number" id="age" name="age" required>
        <br>
        <label for="sex">Sex:</label>
        <input type="text" id="sex" name="sex" required>
        <br>
        <label for="weight">Weight:</label>
        <input type="number" id="weight" name="weight" required>
        <br>
        <label for="height">Height:</label>
        <input type="number" id="height" name="height" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <button type="submit">Submit</button>
    </form>

    <script>
        document.getElementById('basicInfo').addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            const formData = new FormData(this);

            fetch('/userInfo', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                // 可以在这里添加其他逻辑,例如显示成功消息
            })
            .catch((error) => {
                console.error('Error:', error);
            });
        });
    </script>
</body>
</html>

服务器端代码

确保你的服务器能够正确处理 POST 请求并返回 JSON 数据。

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();

// 使用 body-parser 中间件解析请求体
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 连接到 MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

// 定义信息模型
const InfoSchema = new mongoose.Schema({
    age: Number,
    sex: String,
    weight: Number,
    height: Number,
    email: String,
    password: String
});

const Info = mongoose.model('Info', InfoSchema);

// 处理 userInfo 路由
app.post('/userInfo', async (req, res) => {
    try {
        const info = new Info(req.body);
        await info.save();
        console.log(info);
        res.json({ message: 'Data saved successfully' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'An error occurred' });
    }
});

// 启动服务器
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

通过这种方式,你可以避免页面跳转,同时将表单数据上传到服务器。客户端的 JavaScript 代码会拦截表单的提交事件,并通过 Fetch API 发送异步请求。服务器端则处理这些请求并将响应返回给客户端。


把表单target属性指向一个iframe即可。

可以举个简单的例子吗? 谢谢啊

你放个隐藏的iframe,然后把form表单的target属性设置为iframe的name,就可以把标单

表单提交到那里去了,具体代码你谷歌下,很多的

ajax 不能解决么?

同意,ajax 就是干这个的。

为啥不用ajax

后来用$.post推送。没有用表单提交的去 提交数据。

好的。谢谢哈。

ajax+1,表单submit事件的回调 return false即可

为了防止表单提交后的页面跳转,你可以使用AJAX(Asynchronous JavaScript and XML)异步请求来提交表单数据。这样,页面不会因为提交表单而刷新或跳转。

客户端(HTML + JavaScript)

首先,你需要修改你的表单结构,并添加一个JavaScript事件监听器来捕获表单提交事件并用AJAX发送数据。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Upload Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('form').on('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为
        
        var formData = $(this).serializeArray(); // 获取表单数据
        
        $.ajax({
            url: '/userInfo',
            type: 'POST',
            data: formData,
            success: function(response) {
                console.log("Data saved successfully:", response);
            },
            error: function(error) {
                console.error("Error saving data:", error);
            }
        });
    });
});
</script>
</head>
<body>
<form action="/userInfo" method="post" name="basicInfo">
    <input type="text" name="age" placeholder="Age">
    <input type="text" name="sex" placeholder="Sex">
    <input type="text" name="weight" placeholder="Weight">
    <input type="text" name="height" placeholder="Height">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Submit</button>
</form>
</body>
</html>

服务器端(Node.js)

确保你的服务器端代码能够处理AJAX请求。这通常意味着你的服务器需要正确设置Content-Type头以处理JSON或URL编码的数据。

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// 使用中间件解析请求体
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/userInfo', (req, res) => {
    const info = {
        age: req.body.age,
        sex: req.body.sex,
        weight: req.body.weight,
        height: req.body.height,
        email: req.body.email,
        password: req.body.password
    };

    console.log(info);
    // 返回响应,告诉客户端数据已成功保存
    res.json({ status: "success", message: "Data saved successfully" });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

解释

  • 客户端:通过jQuery监听表单的submit事件,并使用event.preventDefault()阻止默认提交行为。然后,使用$.ajax发送表单数据到服务器。

  • 服务器端:使用body-parser中间件解析请求体,并返回一个简单的JSON响应,告知客户端数据是否成功保存。

这种方法可以避免页面跳转,同时实现了数据的异步提交。

回到顶部