404 hataları ExpressJS'deki bir sayfaya nasıl yönlendirilir?


Yanıtlar:


274

Bu örneği oldukça faydalı buldum:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

Yani aslında bu kısım:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

Lütfen "ele" tanımlayın? Rotayı tam olarak ele alınan nedir?
Timo Huovinen

1
Bu noktaya kadar eşleşen bir rota bulunamadı.
Felix

2
Bilginize, app.routerartık kullanımdan kaldırıldı. Bkz. Github.com/strongloop/express/wiki/…
iX3

2
JSON yanıt alabilmek için kullanmak daha iyi olabilir res.jsonyerine res.send(). Kodunuzda aynı şekilde davranırlar, ancak kullanmak res.jsonnesneleri otomatik olarak dizilere dönüştürmeyecek bir sihir yapar .send(). Eşeği sağlam kazığa bağlamak. expressjs.com/api.html#res.json
wgp


158

Bence önce tüm rotalarınızı tanımlamalı ve son rota ekledikçe

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.status(404).send('what???');
});

Çalışan bir uygulama:

app.js:

var express = require('express'),
    app = express.createServer();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.send('hello world');
});

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.send('what???', 404);
});

app.listen(3000, '127.0.0.1');

alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt 

.
./app.js
./public
./public/README.txt

alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?

6
Peki ... sorun şu ki, "*" zaten .js ve .css dosyaları ile eşleşir ve uygulamada belirtilmezler ... iyi, tam olarak yakalamak için bir yol olup olmadığını bilmiyorum aynı şey 404 hatası veya "alınamıyor ..." iletisinin üzerine yazmak için bir yol. Her neyse, teşekkürler

1
Statik ara katman yazılımı mı kullanıyorsunuz, çünkü statik dosyaları sunmaya devam edebilirsiniz?
Alfred

4
app.get('/public/*', function(req, res){ res.sendfile(__dirname + '/public/' + req.url); })statik yol göndermek için bu yolu kullanabilirsiniz. yukarıdaki "*" yolu ile iyi çalışır. app.use(express.static(__dirname + '/public'));benim için çalışmıyor, kablolu.
Chris

25
Bu benim için çalışma değildi, ama sonra benim keşfetti app.use(express.static(...))sonra geldi app.use(app.router). Onları değiştirdiğimde her şey yolunda gitti.
Stephen

5
Cevabınıza @ Stephen'ın yorumunu eklemek için +1. App.use (express.tatic (...))
app.use

37

Bir NotFoundhata oluşturan en son konuma bir ara katman yazılımı koyabilir
veya hatta 404 sayfasını doğrudan görüntüleyebilirsiniz:

app.use(function(req,res){
    res.status(404).render('404.jade');
});

10
Lütfen bir dahaki sefere biraz daha ayrıntılı bir cevap düşünün ... Örnekler genellikle iyidir - ve bu iyi bir örnektir - ancak bazı açıklamalar da çok, çok iyi olabilir ...
Tonny Madsen

2
+1 Çok iyi! Bence bu son rotadan daha iyi, çünkü bu şekilde son seferde use()senin olması gerekmiyor app.router. (benim durumumda olduğu gibi)
Alba Mendez

Ayrıca, bu herhangi bir istek (yalnızca değil GET) varsayılan davranış yerini alır . POSTDiğer yöntemle rastgele bir URL deneyin ; varsayılan değeri döndürür Cannot POST.... Bir saldırgan Express.JS kullandığınızı bilir.
Alba Mendez

Ejs kullanma dışında çok iyi sadece koymak zorundares.render('404')
locrizak

Bu muhtemelen bir statüye sahip olmalıdır (404) res.status (404) .render ('404')
MartinWebb

32

Yukarıdaki cevaplar iyidir, ancak bunların yarısında HTTP durum kodunuz döndürüldüğünde 404 elde edemezsiniz ve diğer yarısında özel bir şablon oluşturma işleminiz olmaz. Expressjs'de özel bir hata sayfasına (404) sahip olmanın en iyi yolu

app.use(function(req, res, next){
    res.status(404).render('404_error_template', {title: "Sorry, page not found"});
});

Bu kodu tüm URL eşlemelerinizin sonuna yerleştirin.


@SushantGupta - 'Geçerli varolan URL eşlemeleri' ile ne demek istiyorsun?
Jonathan Bechtel

@JonathanBechtel Hatalı olmayan URL rotalarınızdan sonra yukarıdaki kod bloğunda olduğu gibi.
Sushant Gupta

6

App.js'nin son satırında bu işlevi koymanız yeterlidir. Bu, varsayılan sayfa bulunamadı hata sayfasını geçersiz kılar:

app.use(function (req, res) {
    res.status(404).render('error');
});

Geçerli bir işleyicisi olmayan tüm istekleri geçersiz kılar ve kendi hata sayfanızı oluşturur.


2
Yardımcı olan "app.js'nin son satırı" yorumunuz oldu! Teşekkürler!
C0NFUS3D

Uygulamama bir özellik eklendi. Thanks :)
Pramesh Bajracharya

5

Sorunuzun cevabı:

app.use(function(req, res) {
    res.status(404).end('error');
});

Ve bunun neden en iyi yol olduğu hakkında harika bir makale var .


1
Arasındaki fark nedir sendve end?
Timo Huovinen

bence o-miss-write olması gerektiğini düşünüyorumsend
Zaid abu khalaf

4

express-error-handler hatalarınız için özel şablonlar, statik sayfalar veya hata işleyicileri belirlemenizi sağlar. Ayrıca, 4xx hata DOS saldırılarına karşı koruma ve kurtarılamayan hatalarda zarif kapatma gibi her uygulamanın gerçekleştirmesi gereken diğer yararlı hata işleme şeyleri de yapar. İstediğinizi nasıl yapacağınız aşağıda açıklanmıştır:

var errorHandler = require('express-error-handler'),
  handler = errorHandler({
    static: {
      '404': 'path/to/static/404.html'
    }
  });

// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );

// Handle all unhandled errors:
app.use( handler );

Veya özel bir işleyici için:

handler = errorHandler({
  handlers: {
    '404': function err404() {
      // do some custom thing here...
    }
  }
}); 

Veya özel bir görünüm için:

handler = errorHandler({
  views: {
    '404': '404.jade'
  }
});

4

Özellikle partiye geç / rota getiren bir eşzamansız yönlendirme işleviniz varsa, 404 sayfasının son yol olarak yürütülmek üzere yazılamayacağı bazı durumlar vardır. Aşağıdaki durumlar bu durumlarda benimsenebilir.

var express = require("express.io"),
    app = express(),
    router = express.Router();

router.get("/hello", function (req, res) {
    res.send("Hello World");
});

// Router is up here.
app.use(router);

app.use(function(req, res) {
    res.send("Crime Scene 404. Do not repeat");
});

router.get("/late", function (req, res) {
    res.send("Its OK to come late");
});

app.listen(8080, function (){
    console.log("Ready");
});

2
Harika, teşekkürler! Ekspresin doğrusal işlenmesine dayanmayan tek cevap (?) (Yani "hata işleyiciyi sonuna koy").
Nick Grealy


2
// Add this middleware
// error handler
app.use(function(err, req, res, next) {
 // set locals, only providing error in development
   res.locals.message = err.message;
   res.locals.error = req.app.get('env') === 'development' ? err : {};

 // render the error page
   res.status(err.status || 500);
   res.render('error');
  });

2

Bunu yapmanın en kolay yolu, Hata Sayfası için tümünü yakalamaktır

// Step 1: calling express
const express = require("express");
const app = express();

Sonra

// require Path to get file locations
const path = require("path");

Artık tüm "html" sayfalarınızı ("html" sayfası hatası dahil) bir değişkende saklayabilirsiniz

// Storing file locations in a variable
var indexPg = path.join(__dirname, "./htmlPages/index.html");
var aboutPg = path.join(__dirname, "./htmlPages/about.html");
var contactPg = path.join(__dirname, "./htmlPages/contact.html");
var errorPg = path.join(__dirname, "./htmlPages/404.html"); //this is your error page

Şimdi Get Yöntemini kullanarak sayfaları çağırmanız ve app.get ("*") kullanarak hata sayfanıza yönlendirmek için mevcut olmayan tüm yollar için tümünü yakalamanız yeterlidir.

//Step 2: Defining Routes
//default page will be your index.html
app.get("/", function(req,res){
  res.sendFile(indexPg);
});
//about page
app.get("/about", function(req,res){
  res.sendFile(aboutPg);
});
//contact page
app.get("/contact", function(req,res){
  res.sendFile(contactPg);
});
//catch all endpoint will be Error Page
app.get("*", function(req,res){
  res.sendFile(errorPg);
});

Bağlantı Noktası kurmayı ve sunucuyu Dinlemeyi unutmayın:

// Setting port to listen on
const port = process.env.PORT || 8000;
// Listening on port
app.listen(port, function(){
  console.log(`http://localhost:${port}`);
})

Bu artık tanınmayan tüm uç noktalar için hata sayfanızı göstermelidir!


1

Yukarıdaki yanıtlar doğru olmakla birlikte, bunu IISNODE içinde çalıştırmak isteyenler için de belirtmeniz gerekir

<configuration>
    <system.webServer>
        <httpErrors existingResponse="PassThrough"/>
    </system.webServer>
<configuration>

(aksi takdirde IIS çıktınızı yiyecektir).


2
Teşekkür ederim!!! İnternette bunu bilen tek kişi sensin (ya da en azından bunu paylaş)! şerefe
André Lucas

1

içerik türüne göre hata işleme yapabilirsiniz

Ayrıca, durum koduna göre kullanım.

app.js

import express from 'express';

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// when status is 404, error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    if( 404 === err.status  ){
        res.format({
            'text/plain': () => {
                res.send({message: 'not found Data'});
            },
            'text/html': () => {
                res.render('404.jade');
            },
            'application/json': () => {
                res.send({message: 'not found Data'});
            },
            'default': () => {
                res.status(406).send('Not Acceptable');
            }
        })
    }

    // when status is 500, error handler
    if(500 === err.status) {
        return res.send({message: 'error occur'});
    }
});

404.jade

doctype html

html
  head
    title 404 Not Found

    meta(http-equiv="Content-Type" content="text/html; charset=utf-8")
    meta(name = "viewport" content="width=device-width, initial-scale=1.0 user-scalable=no")

  body
      h2 Not Found Page
      h2 404 Error Code

Res.format komutunu kullanabiliyorsanız, basit hata işleme kodu yazabilirsiniz.

res.format()Bunun yerine öneri res.accepts().

Önceki kodda 500 hatası oluşursa if(500 == err.status){. . . }çağrılır


1

Merhaba lütfen cevabı bul

const express = require('express');
const app = express();
const port = 8080;

app.get('/', (req, res) => res.send('Hello home!'));
app.get('/about-us', (req, res) => res.send('Hello about us!'));
app.post('/user/set-profile', (req, res) => res.send('Hello profile!'));
//last 404 page 
app.get('*', (req, res) => res.send('Page Not found 404'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

0

Ekspres-jeneratör paketi kullanıyorsanız:

aşağıdaki (err);

Bu kod sizi 404 ara katman yazılımına gönderir.


0

Özel bir sayfaya göndermek için:

app.get('*', function(req, res){
  if (req.accepts('html')) {
     res.send('404', '<script>location.href = "/the-404-page.html";</script>');
     return;
  }
});

0

Statik bir .ejsdosyada 404 hatasını işlemek için aşağıdaki işleyiciyi kullandım .

Bir rota komut dosyasında bu kodu koyun ve ardından gerektiren file.jsaracılığıyla app.use()içinde senin app.js/ server.js/ www.js(NodeJS Intellij kullanılıyorsa)

Statik bir .htmldosya da kullanabilirsiniz .

//Unknown route handler
 router.get("[otherRoute]", function(request, response) {
     response.status(404);
     response.render("error404.[ejs]/[html]");
     response.end();
 });

Bu şekilde, çalışan ekspres sunucu uygun bir şekilde yanıt verir 404 errorve web siteniz, sunucunun 404 yanıtını düzgün bir şekilde görüntüleyen bir sayfa da içerebilir. Ayrıca içerebilir navbarki 404 error templateweb sitenizin diğer önemli içeriğe bu bağlantılar.


0

Hata sayfalarına işlevlerinizden (rotalardan) yönlendirmek istiyorsanız, aşağıdaki şeyleri yapın -

  1. App.js'nize genel hata mesajları kodu ekleyin -

    app.use(function(err, req, res, next) {
        // set locals, only providing error in development
        res.locals.message = err.message
        res.locals.error = req.app.get('env') === 'development' ? err : {}
    
        // render the error page
        // you can also serve different error pages
        // for example sake, I am just responding with simple error messages 
        res.status(err.status || 500)
       if(err.status === 403){
           return res.send('Action forbidden!');
       }
    
       if(err.status === 404){
           return res.send('Page not found!');
       }
    
       // when status is 500, error handler
       if(err.status === 500) {
           return res.send('Server error occured!');
       }
       res.render('error')
    })
  2. Fonksiyonunuzda, hata sayfası yönlendirmesi kullanmak yerine önce hata durumunu ayarlayabilir ve ardından kod akışının yukarıdaki koddan geçmesi için next () kullanabilirsiniz.

    if(FOUND){
        ...
    }else{
        // redirecting to general error page
        // any error code can be used (provided you have handled its error response)
        res.status(404)
        // calling next() will make the control to go call the step 1. error code
        // it will return the error response according to the error code given (provided you have handled its error response)
        next()
    }

0

404 sayfası, app.listen.Express çağrısının rota yollarında * desteği vermeden hemen önce ayarlanmalıdır. Bu, her şeye uyan özel bir karakter. Bu, tüm isteklerle eşleşen bir rota işleyici oluşturmak için kullanılabilir.

app.get('*', (req, res) => {
  res.render('404', {
    title: '404',
    name: 'test',
    errorMessage: 'Page not found.'
  })
})

0

İçindeki tüm HTTP fiillerinin kapsamı express

Örtmek için tüm HTTP fiilleri kullanabilirdin kalan tüm yolları:

app.all('*', cb)

Nihai çözüm şöyle görünecektir:

app.all('*', (req, res) =>{
    res.status(404).json({
        success: false,
        data: '404'
    })
})

Yönlendiriciyi sonuna koymayı unutmamalısınız. Çünkü yönlendiricilerin düzeni önemlidir.


0

Yukarıdaki kod benim için çalışmadı.

Bu yüzden gerçekten işe yarayan yeni bir çözüm buldum!

app.use(function(req, res, next) {
    res.status(404).send('Unable to find the requested resource!');
});

Ya da 404 sayfaya bile işleyebilirsiniz.

app.use(function(req, res, next) {
    res.status(404).render("404page");
});

Umarım bu yardımcı olmuştur!


Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.