I have an Express.js/Node.js website hosted with Heroku. If a file can't be found, the server is supposed to send a 404 error (like most websites do). But the error handlers in my code don't work properly. When the client requests a file that doesn't exist, the page will load...and load...and load...forever. How do I make the server stop loading when it detects the file can't be found?
This is the first section of 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');
});
And the following is my error handling middleware (it goes right after the previous part). The first one handles 400x error codes and the second one handles 500x error codes.
// 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!');
});
Call response.end() in your middleware, like so
// Handle 404 error
app.use(function(request, response) {
response.status(400);
response.send("Error 404!");
response.end();
});
This is how I check for errors in my app, one single middleware
app.use((err, req, res, next) => {
if (err.statusCode === 403) {
res.statusCode = 403;
var out = {
message: 'missing/invalid authorization: ' + err.message,
code: err.code,
statusCode: err.statusCode
};
res.end(JSON.stringify(out));
return;
}
next(err);
});
If a middleware does not end the request, it must forward the request to the next middleware, so you need to call next(), the format of a middleware is
app.use((req, res, next) => { //I'm not doing anything, forward the request next(); });
app.use((req, res, next) => { req.send('I ended the request'); //this middleware ended the request }));
I had almost the same issue (in my case it was the page for HTTP 500 that was loading forever) and the problem was with another middleware that I have added myself and which was before the error handler middlewares and inside which I forgot to call next()
:
app.use(function(req: Request, res: Response, next: NextFunction) {
closeConnFromRequestStorage()
next(); // make sure to call to call next
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.