您好,欢迎来到 SO!
我不确定我是否理解您要完成的工作,但一般来说,您的数据流应该是这样的:
在数据库中存储数据:
- 在按钮上添加事件处理程序,它将使用 JS 获取您输入的任务字符串,将其存储在变量中并使用 REST API(例如 XMLHttpRequest)将此变量传递到您的服务器(Express 是好的 nodejs FW)
- 服务器现在连接到 Pool 并将数据发送到特定表,一旦完成,您将收到来自服务器的 HTTP 响应
从数据库中获取数据:
- 使用相同的按钮事件处理程序 - 在收到 http200 后 - 您开始创建
- 元素使用 JS 并附加您收到的字符串作为响应以及 http 状态。
令人困惑的部分 - 当您想要实现的一切都是将新任务附加到表单下方的任务列表时,为什么还要使用数据库?
编辑以进一步解释 API 数据流:
前端:
首先,您需要为您的按钮设置点击处理程序:
<button type="button" onclick="createNewProject()">Click Me!</button>
它会调用类似的函数:
let createNewProject = () => {
const xhr = new XMLHttpRequest() //REST API: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
const method = "post" //HTTP request method: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
const uri = "/createnewproject" //URI which you use to communicate with backend
//putting data you want to send to server together:
newProject = {}
newProject.project_name = document.getElementById("modal_project_name").value
newProject.project_description = document.getElementById("modal_project_description").value
//send REST request:
xhr.open(method, uri)
xhr.setRequestHeader("Content-Type", "application/json")
xhr.send(JSON.stringify(newProject))
//receive response from server and handle it on frontend:
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//do whatever your frontend needs to do
}
}
服务器:
// please note that HTTP request type and URI do match with frontend
app.post("/saveproject", (req, res) => {
let savedProject = req.body; //get data from frontend
persistence.saveProject(savedProject, status => {
res.status(status).send(); //send to persistence
});
});
持久性:
在这里使用 PG。您将需要使用您的数据库服务器和连接的地址创建连接配置文件(基于数据库类型,遵循文档),当然还需要在节点端导入任何需要导入的内容。
module.exports.createNewProject = (newProject, callback) => {
// queryText: SQL query
// queryValues: your data
const queryText = "INSERT INTO projects (project_name, project_description, project_statuses_id, updated_date) VALUES ($1, $2, (SELECT id FROM project_statuses WHERE project_status = 'active'), $3)"
const queryValues = [
newProject.project_name,
newProject.project_description,
newProject.updated_date
]
pool.connect((err, client, done) => {
if (err) {
console.log("PERSISTENCE: ", err)
done(err)
callback(400)
return console.error("POOL CONNECTION ERROR", err.code)
}
client.query(queryText, queryValues, (err, result) => {
if (err) {
console.log("PERSISTENCE: ", err)
done(err)
callback(400)
return console.error("QUERY ERROR", err.code)
}
done()
callback(200) //return HTTP response back to frontend https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
})
})