【问题标题】:Nodejs random queryNodejs随机查询
【发布时间】:2014-11-28 23:42:49
【问题描述】:

我正在尝试使用 ajax 从我的本地数据库中获取一个随机项目。第一次执行 ajax 请求时,我会在每个 ajax 请求返回相同的项目之后得到一个随机项目。

 var express = require('express')
var app = express();
var customers = require('./module');
var pg = require('pg');
var conString = "postgres://postgres:pass@localhost/test";
var client = new pg.Client(conString);



app.get('/res', function(req, res) {


client.connect(function(err) {
          if(err) {
            return console.error('could not connect to postgres', err);
          }
          client.query('SELECT * FROM t_items OFFSET random()*300 LIMIT 1', function(err, result) {
            if(err) {
              return console.error('error running query', err);
            }
            console.log(result.rows[0]);

              res.contentType('json');
              res.send({ some: result.rows[0] });


             client.end();
          });
    });
});


app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.set('port', (process.env.PORT || 5000))
app.use(express.static(__dirname + '/public'))

app.get('/',function(req, res){


    res.render("index");
});

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

如果我尝试将其包装在 app.post('/req' ).... 我无法连接到 postgres [错误:连接终止] 我已经尝试过客户端池,但仍然是同样的问题

【问题讨论】:

  • 不要自己结束连接。它会自行超时而不会结束。所以尝试删除 client.end() 看看是否有帮助。

标签: ajax node.js postgresql express


【解决方案1】:

只需将您的查询移入函数 app.get('/res', function(req, res)

发生这种情况是因为 db 查询只执行一次。为了防止它 - 将您的代码移动到 /res 路由中,它将在每个请求中执行。

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多