node.js - 查询 "AND"Sqlite 3 REST

标签 node.js rest sqlite

我正在尝试使用 node.js 和 sqlite3 制作一个 Restfull 服务器;我有这 2 个表:

CREATE TABLE contact (
    id                   INTEGER       AUTO_INCREMENT,
    names                VARCHAR(20)   NOT NULL,
    last_name            VARCHAR(20),
    email VARCHAR(20),

    PRIMARY KEY(id)
);

CREATE TABLE phone(
    id                   INTEGER        AUTO_INCREMENT,
    id_contact           INTEGER,
    number               INTEGER,
    description          VARCHAR(20),

    PRIMARY KEY(id),
    FOREIGN KEY(id_contact) REFERENCES contact(id)
);

这 2 个插入...

INSERT INTO contact(names, last_name, email) VALUES
('Brian', 'Cardona', 'brian.cardonas@autonoma.edu.co');

INSERT INTO phone(id_contact, number, description) VALUES
(1, 3105056245, 'Móvil');

INSERT INTO phone(id_contact, number, description) VALUES
(1, 8714396, 'Fijo');

REST Nodejs 服务器:

/* Require modules */
var express = require('express');
var sqlite3 = require('sqlite3').verbose();
var bodyParser = require('body-parser');

/* Global objects */
var app = express();
var port = process.env.PORT || 8080;
var db = new sqlite3.Database('contactos.sqlite');

//////////////////////////////////////////////////////////////////

/* Config (request) and (response) */
app.use(bodyParser.json()); // Body parser use JSON data
app.use(bodyParser.urlencoded({ extended: false }));

/* Support for CORS */
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,    Content-Type, Accept");
next();
});

//////////////////////////////////////////////////////////////////
/* Init db */
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS contact (id INTEGER PRIMARY KEY  AUTOINCREMENT, names  VARCHAR(20) NOT NULL, last_name VARCHAR(20), email  VARCHAR(20));");
db.run("CREATE TABLE IF NOT EXISTS phone (id INTEGER PRIMARY KEY AUTOINCREMENT, id_contact INTEGER, number  INTEGER NOT NULL, description VARCHAR(20), FOREIGN KEY(id_contact) REFERENCES contact(id));");
});

//////////////////////////////////////////////////////////////////
// My routes                                                    //
//////////////////////////////////////////////////////////////////

app.get('/', function(req, res){
res.send('Agenda de contactos!');
});

//////////////////////////////////////////////////////////////////

/* List ALL phones from an specifict contact */
app.get('/phones/contacts/:id_contact', function(req, res, next) {
// MIME Answer
res.setHeader("Content-Type", "application/json");
// Query
db.all("SELECT * FROM phone WHERE id_contact = ?", [req.params.id_contact],    function(err, rows) {
    // If error
    if (err) {
    console.error(err);
    res.status(500);    // Server Error
    res.json({ "error" : err });
    } else {
        // Success
        res.status(200);    // OK
        // Return query
        res.json({ "phones" : rows });
    }
  });
});

//////////////////////////////////////////////////////////////////

/* Get an specifict phone from an specifict contact */
app.get('/phones/:id_phone/contacts/:id_contact', function(req, res, next) {
// MIME answer
res.setHeader("Content-Type", "application/json");
// Query
db.get("SELECT * FROM phone WHERE id = ? AND id_contact = ?",  [req.params.id_phone], [req.params.id_contact], function(err, row) {
    // If error
    if (err) {
    console.error(err);
    res.status(500);        // Server Error
    res.json({ "error" : err });
    } else {
        // Correct answer
        if(row == undefined) {
        // If Resource not found
        res.status(404);    // Registro no encontrado
        res.json({ "error" : "Resource not found" });
        } else {
          // Success
          res.status(200);  // OK
          // Return query
          res.json({ "phone" : row });
        }
      }
     res.end();
   });
});

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

/* Begin the server */

app.listen(port);

console.log('Server listening on port ' + port);

//////////////////////////////////////////////////////////////////

嗯...问题是当我尝试获取特定数量的“Brian”时;我的意思是我尝试访问路由:http://localhost:8080/phones/2/contacts/1 我收到一个错误,它说:{"error":"Resource not found"} 我不明白为什么,因为当我访问路由时:http://localhost:8080/phones/contacts/1 然后我得到了联系人的所有电话号码id=1 在这种情况下,所有带有 id_contact = 1 的号码都来找我...

{"phones":[{"id":1,"id_contact":1,"number":3105056245,"description":"Móvil"},{"id":2,"id_contact":1,"number":8714396,"description":"Fijo"}]}

谢谢你帮助我。

最佳答案

此错误与您的路线无关。您的 db.get 语句似乎有问题。

尝试将值放在一个数组中,如下所示:

db.get("SELECT * FROM phone WHERE id = ? AND id_contact = ?",  [req.params.id_phone, req.params.id_contact], function(err, row)

关于node.js - 查询 "AND"Sqlite 3 REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960309/

相关文章:

node.js - 如何在请求中使用 cookie(request、tough-cookie、node.js)

node.js - 如何打印键中有逗号的 JSON 元素?

node.js - 如何在 Node.js 中使用 EventEmitter

C++:sqlite3 是否使用 errno 代码?

node.js - 使用 Passport 在 express 中找不到用户的凭据

java - Tomcat 上的 Jersey REST 服务出现 404 错误

java - 从 TOMCAT 迁移到 IBM Websphere 时出现 ORA-01017 用户名/密码无效

java - 使用 rest-assured 作为通用的 http 客户端

SQLite:无法删除数据库中的行

sql - 如何在 SQLite 中合并多个数据库文件?