gpt4 book ai didi

node.js - NodeJS Mongoose 将事件插入到 public/index.html

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:23 25 4
gpt4 key购买 nike

我正在学习nodejs,我有一个项目,我希望用户发布表单数据,然后填充位于public/index.html中的html表。

目前,我正在使用以下代码将提交的数据写入数据库集合:

const mongoose = require('mongoose')
const express = require('express');
const app = express();
const server = app.listen(3000);

app.use(express.json()); // for retrieving form data
app.use(express.static('public'));

mongoose.connect('mongodb://localhost/class', {useNewUrlParser: true})
.then( () => console.log('Connected to class database'))
.catch( () => console.error('Connection attempt to class database failed'))
const personSchema = new mongoose.Schema({
name: String,
date: {type: Date, default: Date.now}
})
const Person = mongoose.model('Person', personSchema)


app.post('/join_class', (req,res) => {
res.send('... joining class')
console.debug(req.body.name)
// document.getElementById('class_table').insertRow(req.body.name)
joinClass(req.body)
})

async function joinClass(data){
console.log(data)
person = new Person({
name: data.name
})
await person.save();
}

我的问题是我需要相同的数据来填充位于我的 public/index.html 中的 HTML 表,但当然我无权访问 index.js 中的文档对象。 index.html 文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js'></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- <script src="/client.js"></script> -->
<title>TestING</title>
</head>
<body>
<table id='class_table'>
<tr><th>Class</th></tr>
<tr><td>testing</td></tr>
</table>
</body>
</html>

那么,如何创建 mongoDB 事件/警报,以便当将发布数据插入数据库时​​,相同的数据可用于 index.html,我可以在其中使用文档对象来填充表?

最佳答案

下面是一个示例,您可以在其中添加新的人员,index.html 页面中的列表应在成功插入后更新。

index.js

app.post('/join_class', (req, res) => {
var person = new Person({
name: req.body.name
});
person.save().then((data) => {
res.send(data);
}).catch((err) => {
res.status(500).send(err);
});
})

app.get('/class', (req, res) => {
Person.find({}).then((data) => {
res.send(data);
}).catch((err) => {
res.status(500).send(err);
});
})

index.html(正文标签内容)

<body>
<div>
Name:<br>
<input type="text" id="name" value="">
<br>
<button onclick="addPerson()">Add Person</button>
</div>
<br/>
<b>Person's in List: </b>
<ul id='class_table'>

</ul>
<script src="/client.js"></script>
</body>

客户端.js

function listPerson() {
var req = new XMLHttpRequest();
req.open("GET", '/class');
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var aList = JSON.parse(req.responseText),
list = document.getElementById("class_table");
list.innerHTML = "";
aList.forEach(e => {
var item = document.createElement("li");
item.innerHTML = e.name;
list.appendChild(item);
});

}
};
req.send();
}

function addPerson() {
var req = new XMLHttpRequest();
req.open("POST", '/join_class');
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { listPerson(); } //Get list of Person on completion
};
var sName = document.getElementById("name").value;
req.send(JSON.stringify({ "name": sName }));
}

//Initially load a list of Person's
listPerson();

关于node.js - NodeJS Mongoose 将事件插入到 public/index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56559648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com