我正在构建一个express.js应用程序,它只从mysql数据库中获取数据并显示在屏幕上,我也在尝试实现插入功能,这样我也可以通过浏览器添加数据库,当我发布结果时,其中一个路由点会返回空括号,我不知道为什么,如果有任何帮助,我将不胜感激。
下面的Index.js是addCountries.ejs
//brings you too add Country
app.get("/addCountries", (req, res) => {
res.render("addCountries")
console.log("hello")
})
//inserts data from add countries
app.post("/addCountries", (req, res) => {
sqlDAO.addCountry()
.then((data) => {
res.render("addCountries", {
addCountries: data
})
console.log(req.body.co_name)
console.log("hello")
})
.catch((error) => {
res.send(error)
console.log("hello")
})
})
<h1>Add Country</h1>
<br>
<br>
<form action="/addCountries" method="POST">
<label for="cCode">Country Code:</label>
<input type="text" id="cCode" name="co_code"><br><br>
<label for="cName">Country Name:</label>
<input type="text" id="cName" name="co_name"><br><br>
<label for="CDetails">Country Details:</label>
<textarea type="text" id="CDetails" name="co_details"></textarea>
<input type="submit" value="Add">
</form>
SQLDAO.js
var pool
//creates pool based on database provided by project spec
mysql.createPool({
connectionLimit: 3,
host: 'localhost',
user: 'root',
password: 'password',
database: 'geography'
})
.then((result) => {
pool = result
})
.catch((error) => {
console.log(error)
})
var addCountry = function() {
// returns new promise
return new Promise((resolve, reject) => {
// function that adds too database
var myQuery = {
sql: "INSERT INTO country VALUES (?, ?, ?)",
values: [req.body.co_code, req.body.co_name, req.body.co_details]
}
pool.query(myQuery)
.then((data) => {
resolve(data)
console.log(data)
})
.catch(error => {
reject(error)
})
})
}
您需要将对请求对象的引用传递给addCountry()
。这是因为SQLDAO.js
文件中的addCountry()
函数无法访问请求对象。
现在,在addCountry()
中,req
变量是未定义的,因此在编译SQL语句时没有数据可插入。如果你在数据库中查看,你可能会看到空的或没有添加任何记录。
通过传入请求对象,它可以将数据放入数据库,数据库可以返回这些数据。
像这样编辑两个文件:
sqlDAO.addCountry(req)...
然后var addCountry = function(req) {...
有两个原因是必要的:
-
在
app.post()
函数内部,req
和res
都在该函数的本地范围内,在该函数之外不可用。 -
即使它们是伪全局的,变量也只能在创建它们的模块中使用。因此,您必须导出该变量,或者在这种情况下,将对该变量的引用传递给其他模块中的其他函数。