Jake
Jake

Reputation: 199

Server Not Listening Express

I'm creating a project on express to make "Flask" in nodejs. But for some reason, it doesn't listen at all. In the console, it shows listening on *:8080, but the page doesn't show. Code:

index.js

const { Flask, render_template } = require('./flask');
const app = Flask(__dirname);

app.route('/',()=>render_template('index.html'),);

app.run(8080,'0.0.0.0',(p,h)=>{
  console.log('\nlistening on *:'+p)
});

flask.js

const express = require('express');
const app = express();
const fs = require('fs');

let request = {
  cookies: {
    get: (cookie)=>{},
    obj: {}
  },
  headers: {}
}

app.use((req,res)=>{
  const headers = req.headers;
  delete headers.host;
  delete headers['user-agent'];
  delete headers.accept;
  delete headers['accept-encoding'];
  delete headers['accept-language'];
  delete headers['if-none-match'];
  delete headers['referer'];
  delete headers['sec-ch-ua'];
  delete headers['sec-ch-ua-mobile'];
  delete headers['sec-ch-ua-platform'];
  delete headers['sec-fetch-dest'];
  delete headers['sec-fetch-mode'];
  delete headers['sec-fetch-site'];
  delete headers['sec-fetch-user'];
  delete headers['upgrade-insecure-requests'];
  delete headers['x-forwarded-for'];
  delete headers['x-forwarded-proto'];
  request.headers = headers;
});
function readdir(dirname, onFileContent, ) {
  fs.readdir(dirname,function(err, filenames) {
    onFileContent(filenames);
  });
};
function isDir(path) {
  try {
    var stat = fs.lstatSync(path);
    return stat.isDirectory();
  } catch (e) {
    return false;
  }
}
app.use(require('cookie-parser')())
if(fs.existsSync('static')){
  app.use(express.static('static'))
};

app.use((req,res,next)=>{
  let entr = Object.entries(req.cookies);
  for(var i=0;i<entr.length;i++){
    if(typeof(entr[i][1])=='object'){
      entr[i][1] = JSON.stringify(entr[i][1]);
    }
    request.cookies.obj[entr[i][0]] = entr[i][1];
  }
});

function setErrorStatus(code, callback){
  if(!file){
    app.use((err,req,res,next)=>{
      const status = res.statusCode;
      res.status(status==200?500:code);
      callback({
        redirect: (loc)=>{res.redirect(loc);next()},
        send_file: (fileName)=>{res.sendFile(fileName);next()}
      });
    });
  };
}

function route(dir,call,method="GET"){
  if(method == 'GET'){
    app.get(dir,(req,res)=>{
      res.send(call());
    });
  } else if (method == 'POST'){
    app.post(dir,(req,res)=>{
      res.send(call());
    });
  } else if (method == 'ALL'){
    app.all(dir,(req,res)=>{
      res.send(call());
    });
  } else {
    app.get(dir,(req,res)=>{
      res.send(call())
    })
  }
};

function render_template(file){
  try{
    return fs.readFileSync(__dirname+'/templates/'+file,'utf8')
  } catch (e) {
    let htii;
    console.error(`Error: ENOENT\nNo file/dir called "templates/${file}.`);
    process.exit(73);
  }
}

function run(port=8080,host='0.0.0.0',callback=()=>{}){
  app.listen(port,host='0.0.0.0');
  return callback(port, host);
}

function flask(){
  return {
    route: route,
    run: run,
    // on: appon
  }
}

function send_file(
fileName_or_fp,
as_download = false
){
  if(res == null){ return; };
  if(as_download){
    res.download(fileName_or_fp);
  } else {
    res.render(fileName_or_fp);
  }
}
module.exports = {
  Flask: flask,
  render_template: render_template,
  request: request
}

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Page</title>
</head>
<body>
  <p>Flask Loaded!</p>
</body>
</html>

When I load it for the first time, it shows a blank page, even though it should show the /templates/index.html file after loading.

What I Tried:

Please help.

Note: This is not a duplicate of another question.

Upvotes: 1

Views: 820

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

According to the documentation on middleware, your middleware gets passed a third argument, a next function you should call to pass the request to the next middleware or final route handler. For example:

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

In your first app.use where you delete those headers, you don't accept that argument, therefore Express stops doing anything after your middleware, including not sending a response.

Upvotes: 2

Related Questions