【发布时间】: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