programing

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

jooyons 2023. 6. 4. 10:29
반응형

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.json({ 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 오류, 오류,
도 합니다.

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

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

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

이 코드를 모든 URL 매핑의 끝에 배치합니다.

app.js의 마지막 줄에 이 기능을 넣기만 하면 됩니다.이렇게 하면 기본 페이지를 찾을 수 없음 오류 페이지가 재정의됩니다.

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

유효한 처리기가 없는 모든 요청을 무시하고 사용자 자신의 오류 페이지를 렌더링합니다.

질문에 대한 대답은 다음과 같습니다.

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

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

express-error-message를 사용하여 오류에 대한 사용자 정의 템플릿, 정적 페이지 또는 오류 처리기를 지정할 수 있습니다.또한 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'
  }
});

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

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

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

이것이 노드 보일러 플레이트가 수행하는 작업입니다.

위의 코드는 저에게 맞지 않았습니다.

그래서 저는 실제로 효과가 있는 새로운 해결책을 찾았습니다!

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

또는 404페이지로 렌더링할 수도 있습니다.

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

이것이 당신에게 도움이 되었기를 바랍니다!

// 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 Method를 사용하여 페이지를 호출하고 app.get("*")을 사용하여 오류 페이지로 이동할 수 없는 모든 경로에 대해 catchall을 설정합니다.

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

Port 및 Listen for 서버를 설정하는 것을 잊지 마십시오.

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

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

안녕하세요 답을 찾아주세요

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

HTTP 사합다니에서 모든 합니다.express

모든 HTTP 동사와 나머지 모든 경로를 포함하기 위해 다음을 사용할 수 있습니다.

app.all('*', cb)

최종 솔루션은 다음과 같습니다.

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

당신은 라우터를 마지막에 놓는 것을 잊어서는 안 됩니다.라우터의 순서가 중요하기 때문입니다.

Express에서는 404개의 응답이 오류의 결과가 아니므로 오류 처리기 미들웨어가 이를 캡처하지 않습니다.404 응답을 처리하기 위해 스택의 맨 아래(다른 모든 기능 아래)에 미들웨어 기능을 추가하기만 하면 됩니다.

app.use(function (req, res, next) {
// YOU CAN CREATE A CUSTOM EJS FILE TO SHOW CUSTOM ERROR MESSAGE
  res.status(404).render("404.ejs")
})

위의 답변이 올바르지만 IISNODE에서 이 작업을 수행하려는 사용자의 경우에도 지정해야 합니다.

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

web.config에 저장합니다. 그렇지 않으면 IIS가 출력을 먹어 치웁니다.

내용 유형에 따라 처리 오류가 발생할 수 있습니다.

또한 상태 코드에 따른 처리.

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을 사용할 수 있다면 간단한 오류 처리 코드를 작성할 수 있습니다.

»res.format()res.accepts().

코드인 이전코서에 500 발생하면에서 오류가 발생하면,if(500 == err.status){. . . }를 합다니고라고 합니다.

이 방법이 더 쉽지만, 당신의 모든 경로 이후에 마지막이 되어야 합니다.

app.use( (req, res) => {
    //render page not found 
    res.render('404')
})

Express-Generator 패키지를 사용하는 경우:

다음(err);

이 코드는 당신을 404 미들웨어로 보냅니다.

사용자 지정 페이지로 보내기

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

의 핸들러를 인 404 했습니다..ejsjava.

에 " " "라는 코드를 해야 합니다.file.js를 통하여app.use()의 신의에app.js/server.js/www.js Node(InteliJ를 사용하는 )JS)

정적 기능을 사용할 수도 있습니다..htmljava.

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

중인 "" "" "" "" ""로합니다.404 error또한 웹 사이트에는 서버의 404 응답을 올바르게 표시하는 페이지가 포함될 수 있습니다.다을포할수있다니습을 포함할 .navbar 그점서에.404 error template웹 사이트의 다른 중요한 콘텐츠로 연결됩니다.

함수(경로)에서 오류 페이지로 리디렉션하려면 다음 작업을 수행합니다.

  1. 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. 함수에서 오류 페이지 리디렉션을 사용하는 대신 오류 상태를 먼저 설정한 다음 next()를 사용하여 위의 코드 흐름을 통과할 수 있습니다.

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

404 페이지는 app.listen 호출 직전에 설정해야 합니다.Express는 경로 경로에서 *를 지원합니다.이것은 어떤 것과도 어울리는 특별한 캐릭터입니다.모든 요청과 일치하는 경로 핸들러를 만드는 데 사용할 수 있습니다.

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

모든 경로를 정의한 후 수행하는 작업은 잠재적인 404를 포착하여 다음과 같은 오류 처리기로 전달하는 것입니다.

    const httpError = require('http-errors');

    ...

    // API router
    app.use('/api/', routes);
    
    // catch 404 and forward to error handler
    app.use((req, res, next) => {
      const err = new httpError(404)
      return next(err);
    });

    module.exports = app;

먼저 경로 js 파일을 만듭니다.그런 다음 error.ejs 파일을 만듭니다(ejs를 사용하는 경우).마지막으로 경로 파일에 다음 코드를 추가합니다.

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

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

반응형