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

标签 node.js node-sqlite3

我正在学习如何将 Sqlite3 与 Node 结合使用,但我遇到了一个奇怪的问题。在我的 React 前端的主 App.js 上的 componentWillMount() 中,我向路由 /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 请求之前设置了状态,这让我认为联系人已添加到联系人表中。

但是当我直接访问 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 时,我得到了这个,

all

当我尝试发布到/add 时,出现错误

错误 [ERR_HTTP_HEADERS_SENT]:将 header 发送到客户端后无法设置 header

虽然我没有向哪里发送多个响应。

最佳答案

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

试试这个:

// 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"
    }
  );

});

关于node.js - 路由返回空数组,即使插入数据库似乎有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54670185/

相关文章:

node.js - 首先加载特定的 Mongoose 模型

javascript - 使用 redis-connect 的外部数据库?

javascript - 数据在函数中使用之前更改

javascript - 在knex SELECT之后访问数组值

javascript - 如何在 node.js 和 SQLite3 中使用 document.querySelector 和 require

javascript - "Unresolved function or method"与 Passport.JS

Node.js、NPM、代理和 node_modules

javascript - 如何使用 jest 在 supertest 中模拟模块?

node.js - 更新 SQLite 数据库而不重新启动应用程序

node.js - SQLite3 Node.js JSON