Tuesday 30 May 2017

nodejs server returns error on first attempt

I want to setup a remote file serving through server, so I code this script:

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');

I returns TypeError: Cannot read property 'url' of undefined on first attempt, after refresh page again, it works perfectly, can anyone please check the code where is the issue ?



via Mr Boota

No comments:

Post a Comment