nodejs服务器在第一次尝试时返回错误

时间:2017-05-30 21:07:54

标签: node.js ubuntu

我想设置一个通过服务器提供服务的远程文件,所以我编写了这个脚本代码:

var http = require('http'),
express = require("express"),
mysql = require('mysql'),
t = false,
request = require('request'),
app = express(),
connection = mysql.createConnection({
  host: 'xxx',
  user: 'xxx',
  password: 'xxx',
  database: 'xxx'
});
app.get('/files/:hash/:title', function(req, res) {
  var hash = req.params.hash;
  connection.query('SELECT * from table WHERE hash="' + hash + '"', function(err, rows) {
    t = rows;
  });
  if (!t) {
    res.writeHead(400, {
      'Content-Type': 'text/plain'
    });
    res.end('token expired');
  } else {
    var lastItem = t.pop(),
    urls = lastItem.url,
    cookies = lastItem.cookies,
    options = {
      url: urls,
      headers: {
        Cookie: cookies
      }
    };
    req.pipe(request(options)).pipe(res);
  }
});
app.get('/*', function(req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });
  res.end('prmission denied');
});
app.listen(8080);
console.log('Server running');

我在第一次尝试时返回TypeError: Cannot read property 'url' of undefined,再次刷新页面后,它运行正常,有人可以检查代码在哪里出问题吗?

1 个答案:

答案 0 :(得分:-1)

我怀疑这是回调:

 connection.query('SELECT * from table WHERE hash="' + hash + '"', 
    function(err, rows) {t = rows; });

在事件循环的下一个刻度上进行评估,而这一行:

urls = lastItem.url, 

在当前范围内进行评估,因此您始终返回先前请求中的数据(这是一种奇怪的行为)。在第一个查询中,我猜测表中没有包含当前哈希值的行,这就是t.pop()undefined的原因。 (请注意,空数组是真实的,这就是if(t){...}执行的原因,即使行数为零)