NodeJS 如何将数据从HTML发送到MongoDB?

kfgdxczn  于 12个月前  发布在  Node.js
关注(0)|答案(3)|浏览(117)

我正在使用node js和express以及Mongo。我有一个简单的程序,通过单选按钮接收用户设置。我有一个提交按钮,但我不知道如何从那里工作。我需要一个新的JS文件将其发送到mongodb吗?我想要的只是让我的html保存首选项并将其存储到数据库中。我应该开始执行哪些步骤?
这里的例子:如果我点击男性并点击提交,我希望男性这个词保存到数据库中。

<html>
  <body>
      <form action="">
        <input type="radio" name="sex" value="male">Male<br>
        <input type="radio" name="sex" value="female">Female
      </form>
  </body>
</html>

字符串

u4dcyp6a

u4dcyp6a1#

首先,你想发送一个http post到node js。
这将告诉你如何做到这一点。How to retrieve POST query parameters?
然后你需要获取这些信息并解析它,然后将其发送到Mongo。
这将向您展示如何使用Nodejs Mongo Driver. http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html执行插入操作

uajslkp6

uajslkp62#

1.正在创建服务器。
1.发送http请求。
1.连接到mongodb。
1.在mongodb中插入数据

kupeojn6

kupeojn63#

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Submission</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

    <h1>Email Submission Form</h1>

    <form id="emailForm">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <button type="button" onclick="submitEmail()">Submit</button>
    </form>

    <script>
  function submitEmail() {
    // Get the email input value
    var emailInput = document.getElementById("email");
    var email = emailInput.value;

    // Validate the email (you may add more sophisticated validation)
    if (!isValidEmail(email)) {
        alert("Invalid email address. Please enter a valid email.");
        return;
    }

    // Construct the MongoDB Atlas Data API endpoint
    var apiKey = 'YOUR_API_KEY'; // Replace with your MongoDB Atlas API key
    var clusterName = 'YOUR_CLUSTER_NAME'; // Replace with your cluster name
    var databaseName = 'YOUR_DATABASE_NAME'; // Replace with your database name
    var collectionName = 'emails';

    var endpointUrl = `https://${clusterName}.mongodb.net/api/atlas/v1.0/groups/${apiKey}/database/${databaseName}/collections/${collectionName}`;

    // Create a new XMLHttpRequest object
    var xhr = new XMLHttpRequest();

    // Configure it to make a POST request
    xhr.open("POST", endpointUrl, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Api-Key", apiKey);

    // Prepare the data to be sent
    var emailData = { "email": email };

    // Convert the data to JSON and send the request
    xhr.send(JSON.stringify(emailData));

    // Handle the response (you may add more error handling)
    xhr.onload = function () {
        if (xhr.status === 201) {
            alert("Email submitted successfully!");
            // You can add more logic here after a successful submission
        } else {
            alert("Error submitting email. Please try again.");
        }
    };
}

function isValidEmail(email) {
    // Basic email validation, you can enhance it as needed
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}
</script>

</body>
</html>

字符串

相关问题