首页 > 解决方案 > 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)
      })

  })
}

标签: javascripthtmlmysqlnode.js

解决方案


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

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

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

像这样编辑两个文件:

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

有两个原因是必要的:

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

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


推荐阅读