SORU
30 HAZİRAN 2011, PERŞEMBE


Nasıl ExpressJS bir sayfa için 404 hataları yönlendirmek için?

Bunu yapmak için bir fonksiyon bilmiyorum, herkes biliyor mu?

CEVAP
21 Mart 2012, ÇARŞAMBA


Bu örnek oldukça faydalı buldum:

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

Aslında bu kısmı öyledir:

// "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');
});

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Damian Winter

    Damian Winte

    27 ŞUBAT 2007
  • Dogbert files

    Dogbert file

    12 Ocak 2012
  • Stevie

    Stevie

    2 Mayıs 2010