App.post 返回空的花括号集

时间:2021-01-01 20:21:50

标签: javascript html mysql node.js

我正在构建一个 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)
      })

  })
}

1 个答案:

答案 0 :(得分:0)

您需要将请求对象的引用传递给 addCountry()。这是因为 addCountry() 文件中的 SQLDAO.js 函数无权访问请求对象。

现在,在 addCountry() 中,req 变量未定义,因此在编译 SQL 语句时没有要插入的数据。如果您查看数据库,您可能会看到添加的记录为空或没有记录。

通过传入请求对象,它可以将数据放入数据库并且数据库可以返回。

像这样编辑两个文件:

sqlDAO.addCountry(req)... 然后 var addCountry = function(req) {...

这是必要的有两个原因:

  1. 在您的 app.post() 函数内部,reqres 都在函数的本地范围内,并且在该函数之外不可用。

  2. 即使它们是伪全局变量,变量也只能在创建它们的模块中使用。因此,您必须导出该变量,或者在这种情况下,将对该变量的引用传递给某个其他模块中的某个其他函数。

相关问题