Javascript 是否从表单将信息保存到MongoDB数据库?
我想将从html表单捕获的信息保存到MongoDB数据库中,我有以下代码:Javascript 是否从表单将信息保存到MongoDB数据库?,javascript,mongodb,express,Javascript,Mongodb,Express,我想将从html表单捕获的信息保存到MongoDB数据库中,我有以下代码: <!DOCTYPE html> <html> <head> <title>Intro to Node and MongoDB</title> </head> <body> <h1>Into to Node and MongoDB</h1> <form method="post" action="
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
</html>
显然,post请求正在工作,填写字段并按输入类型submit,但是当检查数据库是否为空时,就像创建数据库时一样。有人知道我为什么不保存信息吗?我在这里运行了你的代码,但没有调用
app.post
。这是因为您正在使用应用程序。请使用发送index.html
<代码>应用程序。使用
用于绑定到应用程序。相反,您应该使用app.get
,它告诉express侦听对/
的请求,并在看到请求时运行该函数
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
几点建议:一,。尝试将req.body
和myData
记录到控制台,看看它们是否是您所期望的。2.您是否收到服务器的回复?3.如果是,是“项目保存到数据库”还是“无法保存到数据库”?
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});