Saturday 27 May 2017

Webpage loads forever when file can't be found

I have a simple Express.js/Node.js website. If a file can't be found, the server is supposed to send a 404 error. But it doesn't work as expected. Let's say, if an image has the wrong URL, the webpage which the image is on will just keep on loading forever. How do I set up the error handlers properly so it stops loading if it detects a file doesn't exist?

This is my JavaScript:

var express = require('express'); // Express.js
var app = express();
var http = require('http');
var server = http.createServer(app);
var bodyParser = require('body-parser');
var postgres = require('pg'); // Postgres database

app.use(express.static('static', {
    extensions: ['html']
}));



app.all('*', function (request, response, next) {
    var redirectURL = request.query.redirect;
      if (redirectURL != undefined) {
        response.redirect(redirectURL);
      }
});

app.get('/', function (request, response, next) {
  response.redirect('/main/index');
});



// Handle 404 error
app.use(function(request, response) {
    response.status(400);
    response.send("Error 404!");
});

// Handle 500 error
app.use(function(error, request, response, next) {
    response.status(500);
    response.send("Error 500!");
});



server.listen(process.env.PORT || 8080, function () {
  console.log('Listening on port 8080!');
});



via repfarmer

No comments:

Post a Comment