路由返回空数组,即使插入数据库似乎有效

Route returning empty array even though inserting into db seems to be working

我正在学习如何将 Sqlite3 与 Node 一起使用,但我 运行 遇到了一个奇怪的问题。在 componentWillMount() 中,在我的反应前端的主要 App.js 中,我向路由 /all 发出了 axios 请求,因此我可以填充联系人列表。

奇怪的是,当我点击另一条路线时,/add 在我添加联系人时使用不同的 axios 请求,它到达我的 then()

axios
  .post('/add', contactData)
  .then(res =>
    console.log(`Contact ${contactData.name} added successfully`)
  )
  .catch(err => console.log('Error encountered: ', err));

也有一点延迟,因为我在发出 axios 请求之前设置状态,这让我认为联系人已添加到联系人中 table。

但是当我直接访问 localhost:5000/all 时,我收到一个空数组 [] 作为响应。我不确定发生了什么。

这是我的 server.js

const express = require('express');
const sqlite3 = require('sqlite3');
const path = require('path');
const cors = require('cors');

const dbName = 'my.db';
const tableName = 'Contacts';
const dbPath = path.resolve(__dirname, dbName);

const app = express();

const port = process.env.PORT || 5000;

app.use(cors());

app.listen(port, () => console.log(`Server running on port ${port}`));

app.get('/all', (req, res) => {
  let db = new sqlite3.Database(dbPath);

  let sql = `SELECT number FROM ${tableName}`;

  db.run(
    `CREATE TABLE IF NOT EXISTS ${tableName}(name text, number text, address text)`
  );

  db.all(sql, [], (err, rows) => {
    if (err) {
      return res.status(500).json(err);
    } else {
      return res.json(rows);
    }
  });
});

app.post('/add', (req, res) => {
  let db = new sqlite3.Database(dbPath);

  db.run(
    `INSERT INTO ${tableName}(name, number, address) VALUES(${req.name},${
      req.number
    },${req.address})`,
    [],
    err => {
      if (err) return res.status(500).json(err);
    }
  );

  return res.json({ msg: 'success' });
});

编辑:

我应该注意到,当我导航到 /all 时,我得到了这个,

当我尝试 post 到 /add 时,我收到错误消息

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

虽然我没有发送多个回复到哪里。

您可以在 Node.js 中使用 Async-Await 解决此问题。 JavaScript 本质上是异步的,Node.js 也是如此。异步编程是一种保证非阻塞代码执行的设计模式。

非阻塞代码不会阻止一段代码的执行。一般来说,如果我们以同步方式执行,即一个接一个地执行,我们不必要地停止那些不依赖于您正在执行的代码的执行。

异步恰恰相反,异步代码执行时没有任何依赖,没有顺序。这提高了系统效率和吞吐量。

但在某些情况下,我们需要等待响应。

 app.get('/all',async (req, res) => {
  let db = new sqlite3.Database(dbPath);
  let sql = `SELECT number FROM ${tableName}`;
 await db.run(
    `CREATE TABLE IF NOT EXISTS ${tableName}(name text, number text, address text)`
  );
 await  db.all(sql, [], (err, rows) => {
    if (err) {
      return res.status(500).json(err);
    } else {
      return res.json(rows);
    }
  });
});
app.post('/add',async  (req, res) => {
  let db = new sqlite3.Database(dbPath);
  await db.run(
    `INSERT INTO ${tableName}(name, number, address) VALUES(${req.name},${
      req.number
    },${req.address})`,
    [],
    err => {
      if (err) return res.status(500).json(err);
    }
  );
  return res.json({ msg: 'success' });
})
await  db.all(sql, [], async (err, rows) => {
    if (err) {
       await return res.status(500).json(err);
    } else {
     await return res.json(rows);
    }
  });

我不会在你每次点击 /all 时初始化你的数据库并创建你的 table。

试试这个:

// get this out of the `/all` route, no need to initialize the db object over and over again
let db = new sqlite3.Database(dbPath);

// also leave this outside the `/all` route:
// no need to create the table over and over again.
db.run(
  `CREATE TABLE IF NOT EXISTS ${tableName}(name text, number text, address text)`
);


app.get('/all', (req, res) => {
  let sql = `SELECT number FROM ${tableName}`;

  // according to the sqlite3 api, the second parameter is optional, so just leave it out:
  db.all(sql, (err, rows) => {
    if (err) return res.status(500).json(err); // if you use return,  you don't need 'else' because the code will never reach it.

    res.json(rows)
  });
});

您的 /add 路线看起来也有点偏离。试试这个:

app.post('/add', (req, res) => {
  // let db = new sqlite3.Database(dbPath);  // remove this as you already defined it at the beginning of your code.

  db.run(
    `INSERT INTO ${tableName}(name, number, address) VALUES(${req.name},${req.number},${req.address})`,
    err => {
      if (err) return res.status(500).json(err);
      res.json({ msg: 'success' }); // put the success in the callback (after the query is run!), else, when you get an error, express.js will try to send an error message AND a success message giving you the error "Can't send headers after they are sent"
    }
  );

});