IT

ExpressJS에서 404 오류를 페이지로 리디렉션하는 방법은 무엇입니까?

lottoking 2020. 5. 13. 08:20
반응형

ExpressJS에서 404 오류를 페이지로 리디렉션하는 방법은 무엇입니까?


나는 이것을하는 기능을 모른다. 아는 사람이 있습니까?


이 예제가 매우 유용하다는 것을 알았습니다.

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

실제로는이 부분입니다.

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

먼저 모든 경로를 정의하고 마지막 경로를 추가해야한다고 생각합니다.

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

작동하는 예제 앱 :

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?

NotFound오류를 발생
시키거나 404 페이지를 직접 렌더링하는 마지막 위치에 미들웨어를 배치 할 수 있습니다 .

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

위의 답변은 좋지만 절반은 HTTP 상태 코드가 반환되어 404를 얻지 못하고 다른 절반은 사용자 정의 템플릿을 렌더링 할 수 없습니다. Expressjs에서 사용자 정의 오류 페이지 (404)를 얻는 가장 좋은 방법은

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

이 코드를 모든 URL 매핑의 끝에 배치하십시오.


귀하의 질문에 대한 답변은 다음과 같습니다

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

그리고 왜 이것이 가장 좋은 방법인지에 대한 훌륭한 기사가 있습니다 .


app.js의 마지막 줄 에이 함수를 넣으십시오. 기본 페이지를 찾을 수 없음 오류 페이지가 무시됩니다.

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

유효한 핸들러가없는 모든 요청을 무시하고 고유 한 오류 페이지를 렌더링합니다.


https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js

이것이 노드 보일러 플레이트의 기능입니다.


express-error-handler를 사용하면 오류에 대한 사용자 정의 템플릿, 정적 페이지 또는 오류 처리기를 지정할 수 있습니다. 또한 4xx 오류 DOS 공격으로부터 보호하고 복구 할 수없는 오류를 정상적으로 종료하는 등 모든 앱에서 구현해야하는 유용한 오류 처리 기능을 수행합니다. 요청한 작업을 수행하는 방법은 다음과 같습니다.

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 );

또는 사용자 정의 핸들러의 경우 :

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

또는 사용자 정의보기 :

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

404 페이지를 마지막 라우트로 실행할 수없는 경우가 있습니다. 특히 파티에 늦게 / route를 가져 오는 비동기 라우팅 기능이있는 경우입니다. 이 경우 아래 패턴이 채택 될 수 있습니다.

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

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


가장 쉬운 방법은 오류 페이지를 모두 잡아내는 것입니다.

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

그때

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

이제 모든 "html"페이지 (오류 "html"페이지 포함)를 변수에 저장할 수 있습니다

// 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

이제 Get 메소드를 사용하여 페이지를 호출하고 app.get ( "*")을 사용하여 오류 페이지로 안내 할 수없는 모든 경로를 잡을 수 있습니다

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

포트를 설정하고 서버를 청취하는 것을 잊지 마십시오 :

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

인식 할 수없는 모든 엔드 포인트에 대한 오류 페이지가 표시됩니다!


위의 답변은 정확하지만 IISNODE 에서이 작업을 수행하려는 사람들은 다음을 지정해야합니다.

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

web.config에서 (그렇지 않으면 IIS가 출력을 먹습니다).


you can error handling according to content-type

Additionally, handling according to status code.

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

If you can using res.format, You can write simple error handling code.

Recommendation res.format() instead of res.accepts().

If the 500 error occurs in the previous code, if(500 == err.status){. . . } is called


Hi please find the answer

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}!`));

If you use express-generator package:

next(err);

This code send you to the 404 middleware.


To send to a custom page:

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

I used the handler below to handle 404 error with a static .ejs file.

Put this code in a route script and then require that file.js through app.use() in your app.js/server.js/www.js (if using IntelliJ for NodeJS)

You can also use a static .html file.

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

This way, the running express server will response with a proper 404 error and your website can also include a page that properly displays the server's 404 response properly. You can also include a navbar in that 404 error template that links to other important content of your website.


If you want to redirect to error pages from your functions (routes) then do following things -

  1. Add general error messages code in your app.js -

    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. In your function, instead of using a error-page redirect you can use set the error status first and then use next() for the code flow to go through above code -

    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()
    }
    

app.get('*',function(req,res){
 res.redirect('/login');
});

참고URL : https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs

반응형