node.js - Express - 为什么代码永远不会返回?

标签 node.js sqlite express

我是 Express 菜鸟,不明白:为什么下面的代码永远不会返回?它似乎只是挂着。

router.post('/post',function(req,res){

    var file = "test.db"
    var exists = fs.existsSync(file);
    if(!exists) {
        console.log("Creating DB file.");
        fs.openSync(file, "w");
    }
    var sqlite3 = require("sqlite3").verbose();
    var db = new sqlite3.Database(file);

    db.serialize(function() {
        if(!exists) {
            db.run("CREATE TABLE Stuff (thing TEXT)");
        }
        var stmt = db.prepare("INSERT INTO Stuff(thing) VALUES (99999)");
        stmt.finalize();
    });

    db.close();
}); //seems to hang at this line.

最佳答案

您需要调用 res.send 或 res.end 以从请求中返回某些内容并防止其挂起。

router.post('/post',function(req,res){

var file = "test.db"
var exists = fs.existsSync(file);
if(!exists) {
    console.log("Creating DB file.");
    fs.openSync(file, "w");
}
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);

db.serialize(function() {
    if(!exists) {
        db.run("CREATE TABLE Stuff (thing TEXT)");
    }
    var stmt = db.prepare("INSERT INTO Stuff(thing) VALUES (99999)");
    stmt.finalize();
});

db.close();
res.send("<h1>Done</h1>");
}); //seems to hang at this line.

关于node.js - Express - 为什么代码永远不会返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29901410/

相关文章:

mysql - 使用设置值数组通过 myCon.query 更新表

node.js - 在 Windows 上从 Node 关闭另一个进程

ios - 查找每个季度中两个日期之间的天数

node.js - 是否有用于 RequireJS 优化器的 ExpressJS 中间件?

javascript - NodeJS + ExpressJS 压缩什么都不做?

json - 如何使用expressJS在Stormpath中获取自定义用户数据?

javascript - Node.js 事件发射器源码讲解

javascript - 如何正确检测 Node.js 中 JSON 对象中的转义字符?

macos - 如何在 macOS 上加载 Spatialite SQLite 扩展

android - 在装有 Android 6.0 的 LG 手机上,应用程序在 libicuuc.so 中的 native 代码中崩溃