SOS问题请: 我想制作一个简单的待办事项应用程序,以添加待办事项任务并将其保存在数据库mysql中,就像此链接一样: https://www.w3schools.com/howto/howto_js_todolist.asp
但是我想将数据保存在mysql数据库中而不是li html标记中,并在我单击添加(提交按钮)时直接呈现它,例如上面的!! 问题是我找不到连接到数据库后谁可以在nodejs中创建新li元素或谁可以处理数据行的方式! 任何人都有提示! SOS
答案 0 :(得分:0)
您好,欢迎来到!
我不确定我是否理解您要完成的工作,但是通常,您的数据流应如下所示:
在数据库中存储数据:
从数据库获取数据:
令人困惑的部分-当您要实现的所有事情都是在表单下方的任务列表中追加新任务时,为什么还要使用数据库?
编辑以进一步解释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。您将需要使用数据库服务器和连接的地址创建连接配置文件(基于db类型,请参见文档),当然还要导入需要在节点侧导入的任何内容。
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
})
})