我正尝试找出如何将客户端(HTML表单)数据传递到Node / Express / sqlite后端-不确定如何在客户端打包请求和/或在服务器上提取请求一侧。
客户代码:
// listen for the form to be submitted and add a new dream when it is
dreamsForm.onsubmit = function(event) {
// stop our form submission from refreshing the page
console.log("SUBMIT clicked!!!");
event.preventDefault();
// jeng: save the value to post
var data = {dream: dreamInput.value}; // jeng: JSON
const dreamRequest = new XMLHttpRequest();
dreamRequest.open('post', '/putDreams', true);
dreamRequest.setRequestHeader('Content-Type', "application/json;charset=UTF-8"); // jeng - after open but before send
//dreamRequest.send(JSON.stringify(data));
dreamRequest.send(data);
};
服务器代码
// jeng: added insert a new row to the Dreams table
app.get("/putDreams", function (request, response) {
console.log("insertRows called!!");
var stmt = db.prepare("INSERT INTO Dreams VALUES (?)");
var val = request.body.dream;
//var s = JSON.parse("test")
//request.json();
console.log("1 "+request);
console.log("2 "+request.body);
console.log("3 "+request.body.dream);
//console.log("4 "+s);
//stmt.run("test"); // this works!! test is inserted
stmt.run(val); // this doesn't work - val is undefined - null is inserted
stmt.finalize();
response.redirect("/");
});
我的特定需求是简单地获取用户输入的一段文本,然后使用Node / Express将其插入sqlite表中。到目前为止,我到处搜索都无济于事。任何建议/指针将不胜感激。预先感谢