javascript - App.post 返回空的花括号集
问题描述
我正在构建一个 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()
. 这是因为文件addCountry()
内的函数SQLDAO.js
无权访问请求对象。
现在,in变量是未定义addCountry()
的req
,因此在编译 SQL 语句时没有要插入的数据。如果您查看数据库,您可能会看到空的或没有添加记录。
通过传入请求对象,它可以将数据放入数据库并且数据库可以返回。
像这样编辑两个文件:
sqlDAO.addCountry(req)...
然后var addCountry = function(req) {...
有两个原因是必要的:
在您的
app.post()
函数内部req
,两者都在函数的本地范围内,并且res
在该函数之外不可用。即使它们是伪全局的,变量也只能在创建它们的模块中使用。因此,您必须导出该变量,或者在这种情况下,将对它的引用传递给其他模块中的其他函数。
推荐阅读
- jboss - 与设计工作室合作时无法从 T24(TAFJ R18)获取数据
- ios - 将数组保存到 Core Data
- monaco-editor - 摩纳哥语言匹配空行
- django - 当数据库更新时,通过 Django Channels & Websockets 向客户端推送实时更新
- python - 如何在 python 中获取提示(信息提示)文本?(鼠标悬停时出现的弹出文本框)
- docker - docker-compose is not picking up file system changes in shared volume
- php - 在 Chrome 浏览器中输入类型日期为 2018 年 12 月 11 日
- reactjs - 如何在 React 项目中添加 Service Worker
- javascript - 缩小没有jquery的div
- javascript - 使用并行异步请求处理错误