【问题标题】:Cannot POST on JS and MongoDB无法在 JS 和 MongoDB 上发布
【发布时间】:2021-10-24 04:01:57
【问题描述】:

我是 Web 开发的新手,现在我正在尝试构建一个登录页面,该页面使用 HTML、CSS 和 Javascript 用于网站,以及 MongoDB 数据库来存储从用户接收到的数据。我在 YouTube 上学习了一些教程,但由于某些原因无法发布数据。

这是我目前拥有的代码:

(Javascript)

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

app.use(bodyParser.urlencoded( {extended: true}));

mongoose.connect("mongodb+srv://cs196:cs196@userdata.sn7wv.mongodb.net/cs196", { userNewUrlParser: true}, {useUnifiedTopology: true} );

// create a data schema

const notesSchemaCreate = {
    username: String,
    email: String,
    password: String,
    confirm_password: String
}

const Note = mongoose.model("NoteCreate", notesSchemaCreate)

app.get("/", function(req, res) {
    res.sendFile(__dirname + "/index.html");
})

app.post("/", function(req, res) {
    let newNote = new Note({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password,
        confirm_password: req.body.confirm_password
    });
    newNote.save();
})

app.listen(3000, function() {
    console.log("server is running on 3000")
})

(这里是 HTML 代码)

<!DOCTYPE html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <title>Login Site</title>
    <link rel="stylesheet" href="./main.css">
</head>
<body>
    <div class="container">
        <!-- Create an account -->
        <form class="form form--hidden" id="createAccount" method= "post" action="/">

            <h1 class="form__title">Create Account</h1>
            <div class="form__message form__message--error"></div>
            <div class="form__input-group">
                <input type="text" id="signupUsername" class="form__input" name="username" autofocus placeholder="Username">
                <div class="form__input-error-message"></div>
            </div>
            
            <div class="form__input-group">
                <input type="text" class="form__input" name= "email" autofocus placeholder="Email Address">
                <div class="form__input-error-message"></div>
            </div>

            <div class="form__input-group">
                <input type="password" class="form__input" name= "password" autofocus placeholder="Password">
                <div class="form__input-error-message"></div>
            </div>
            
            <div class="form__input-group">
                <input type="password" class="form__input" name= "confirm_password" autofocus placeholder="Confirm Password">
                <div class="form__input-error-message"></div>
            </div>
            <button class="form__button" type="submit">Continue</button>
            <p class="form__text">
                <a class="form__link" href="./" id="linkLogin">Already have an account? Sign In</a>
            </p>
        </form>
    </div>
</body>

我正在使用localhost:3000 尝试结果,如下所示:

结果只是在新页面中给了我cannot POST / 。

请让我知道我的 MongoDB 设置是否有问题,或者如果你想看看现在的设置如何,因为我不知道要向你们展示哪些部分,我不想让这篇文章变得非常长。

提前感谢任何可以帮助我的人!如果我的代码或这篇文章的格式很糟糕,我提前道歉。

【问题讨论】:

  • 除了您在newNote.save(); 行之后缺少res.end() 之外,它似乎有效。继续在您的 post 方法中添加 res.end(),因为它会卡住,直到最终超时。

标签: javascript html mongodb post


【解决方案1】:
  1. 每个端点函数都必须通过发送响应(res.send(), res.json(), res.end() 等)来结束请求-响应周期。
  2. model.create() 是异步的。将您的功能标记为async

所以解决办法是:

app.post("/", async(req, res) => {
    try {
      const newUser = await Note.create({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password,
        confirm_password: req.body.confirm_password
      });

      res.json({status: "success", message: "user created successfully", user: newUser})

    } catch(error) {
        res.json({status: "fail", message: error.message ? error.message : "could not create user"})
    }
    
})

P.S:永远不要公开你的秘密(mongo_uri、stripe_key 等)密钥。

【讨论】:

  • 感谢您的帮助和建议。但是,现在不是将数据推送到 MongoDB,而是在我按“继续”后继续加载。知道是什么导致了这个问题吗?
  • @BryantHsiung 确保您的请求到达正确的端点:app.post("/", function(req, res) { console.log("request has hit with post method"); let newNote = new Note(......... 如果一切正确,您将在 nodejs 控制台中看到该消息。 (不是浏览器控制台)
  • 好的,只是快速更新。我收到了一些"UnhandledPromiseRejectionWarning: Unhandled promise rejection"、"DeprecationWarning: Unhandled promise rejections are deprecated."(实际消息很长,不适合这个评论部分,但我认为基本上是上述错误的重复)。
  • @BryantHsiung “UnhandledPromiseRejectionWarning:未处理的承诺拒绝”,“DeprecationWarning:不推荐使用未处理的承诺拒绝。”意味着您的快速应用程序中没有全局错误处理程序。您应该设置一个全局错误处理程序来捕获任何错误。否则你必须使用try/catch 来处理异步任务
  • @BryantHsiung 如果这能解决您的问题,请告诉我。 (标记为已接受✓)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多