programing

express req 객체를 사용하여 요청 경로를 가져오는 방법

sourcejob 2022. 11. 13. 19:31
반응형

express req 객체를 사용하여 요청 경로를 가져오는 방법

express + node.js를 사용하고 있으며 req 오브젝트가 있습니다.브라우저의 요청은 /account이지만 req.path에 로그인하면 '/account'가 아닌 '/'가 표시됩니다.

  //auth required or redirect
  app.use('/account', function(req, res, next) {
    console.log(req.path);
    if ( !req.session.user ) {
      res.redirect('/login?ref='+req.path);
    } else {
      next();
    }
  });

req.path는 /이것이 /account가 되어야 하는 경우?

직접 플레이를 한 후 다음을 사용해야 합니다.

console.log(req.originalUrl)

경우에 따라서는 다음을 사용해야 합니다.

req.path

이렇게 하면 요청된 전체 URL 대신 경로가 제공됩니다. 예를 들어 사용자가 요청한 페이지에만 관심이 있고 모든 종류의 매개 변수가 아닌 경우 URL:

/myurl.htm?allkinds&ofparameters=true

req.path는 다음을 제공합니다.

/myurl.html

다음으로 매뉴얼에서 확장한 예를 제시하겠습니다.이 예에서는 모든 경우 express를 사용하여 경로/URL에 액세스하기 위해 알아야 할 모든 것을 정리하고 있습니다.

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})

기준: https://expressjs.com/en/api.html#req.originalUrl

결론:c1moore의 답변은 다음과 같습니다.

var fullPath = req.baseUrl + req.path;

8년 후 업데이트:

req.path이미 제가 말씀드린 것과 똑같은 일을 하고 있었습니다이 답변이 어떻게 문제를 해결하고 정답으로 받아들였는지 기억나지 않지만 현재 유효한 답변이 아닙니다.이 답변은 무시해 주세요.이 말을 해주셔서 @mhodges님 감사합니다.

원답:

querystring 없이 "path"만 가져오려면urlurl의 경로 부분만 구문 분석하고 가져옵니다.

var url = require('url');

//auth required or redirect
app.use('/account', function(req, res, next) {
    var path = url.parse(req.url).pathname;
    if ( !req.session.user ) {
      res.redirect('/login?ref='+path);
    } else {
      next();
    }
});

다음 중 하나여야 합니다.

req.url

express 3.1.x

//auth required or redirect
app.use('/account', function(req, res, next) {
  console.log(req.path);
  if ( !req.session.user ) {
    res.redirect('/login?ref='+req.path);
  } else {
    next();
  }
});

req.path는 /이것이 /account가 되어야 하는 경우?

그 이유는 Express가 핸들러 함수가 마운트되어 있는 경로를 감산하기 때문입니다.이것은 다음과 같습니다.'/account'이 경우는,

그들은 왜 이런 일을 할까?

핸들러 기능을 재사용하기 쉽기 때문입니다.다른 작업을 수행하는 핸들러 함수를 만들 수 있습니다.req.path === '/'그리고.req.path === '/goodbye'예를 들어 다음과 같습니다.

function sendGreeting(req, res, next) {
  res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}

그런 다음 여러 엔드포인트에 마운트할 수 있습니다.

app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)

제공:

/world           ==>  Hello there!
/world/goodbye   ==>  Farewell!
/aliens          ==>  Hello there!
/aliens/goodbye  ==>  Farewell!

버전 4.x 의 경우는,req.baseUrl에 더하여req.path풀 패스를 얻을 수 있습니다.예를 들어 OP는 다음과 같은 작업을 수행합니다.

//auth required or redirect
app.use('/account', function(req, res, next) {
  console.log(req.baseUrl + req.path);  // => /account

  if(!req.session.user) {
    res.redirect('/login?ref=' + encodeURIComponent(req.baseUrl + req.path));  // => /login?ref=%2Faccount
  } else {
    next();
  }
});

이는 메인 파일(또는 )과 같은 기본 모듈에서 직접 호출하는 경우와 미들웨어(루트 파일)를 통해 내부 모듈에서 호출하는 경우(예: )와는 다른 결과를 얻을 수 있습니다.

API 호출:
http://localhost:8000/api/users/profile/123/summary?view=grid&leng=en

위의 API 호출과 출력을 비교합니다.


1) 먼저 내부 모듈에서 결과를 확인합니다.

사용자 모듈을 루트 디렉토리 에 배치하고, 1개의 루트를 사용합니다.

routes/users.module

const router = (require('express')).Router();

router.get('/profile/:id/:details', (req, res) => {

    console.log(req.protocol);        // http or https
    console.log(req.hostname);        // only hostname (abc.com, localhost, etc)
    console.log(req.headers.host);    // hostname with port number (if any)
    console.log(req.header('host'));  // <same as above>
    console.log(req.route.path);      // exact defined route
    console.log(req.baseUrl);         // base path or group prefix
    console.log(req.path);            // relative path except path
    console.log(req.url);             // relative path with query|search params
    console.log(req.originalUrl);     // baseURL + url

    // Full URL
    console.log(`${req.protocol}://${req.header('host')}${req.originalUrl}`);

    res.sendStatus(200);

});

module.exports = router;

index.displaces를 표시합니다.

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

const users = require('./routes/users');
app.use('/api/users', users);

const server = require('http').createServer(app);
server.listen(8000, () => console.log('server listening'));
산출량

http[당황]
localhost[★★★★★★★★★★★★★★★★★★」
localhost:8000[호스트 호스트]
localhost:8000[아쉬움]
/profile/:id/:details[ path] 스스 ]
/api/users]
/profile/123/summary]..............................................[당황]
/profile/123/summary?view=grid&leng=en........................ [url]
/api/users/profile/123/summary?view=grid&leng=en]..[오리지널 URL]

URL 체 url URL:
http://localhost:8000/api/users/profile/123/summary?view=grid&leng=en


2) 이제 메인 모듈에서 직접:

시작 파일(app.js 또는 index.js)에서 경로를 정의합니다.

index.displaces를 표시합니다.

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

app.get('/api/users/profile/:id/:details', (req, res) => {

    console.log(req.protocol);        // http or https
    console.log(req.hostname);        // only hostname (abc.com, localhost, etc)
    console.log(req.headers.host);    // hostname with port number (if any)
    console.log(req.header('host'));  // <same as above>
    console.log(req.route.path);      // exact defined route
    console.log(req.baseUrl);         // base path or group prefix
    console.log(req.path);            // relative path except path
    console.log(req.url);             // relative path with query|search params
    console.log(req.originalUrl);     // baseURL + url

    // Full URL
    console.log(`${req.protocol}://${req.header('host')}${req.originalUrl}`);

    res.sendStatus(200);

});

const server = require('http').createServer(app);
server.listen(8000, () => console.log('server listening'));
산출량

http[당황]
localhost[★★★★★★★★★★★★★★★★★★」
localhost:8000......................................................[호스트 호스트]
localhost:8000......................................................[아쉬움]
/profile/:id/:details..................................................................................................[ path] 스스 ]
]
/profile/123/summary]..................................[당황]
/profile/123/summary?view=grid&leng=en [url]
/profile/123/summary?view=grid&leng=en [ 리널 url] URL ]

URL 체 url URL:
http://localhost:8000/api/users/profile/123/summary?view=grid&leng=en

위의 출력에서 유일하게 다른 점은baseUrl여기 빈 문자열이 있습니다.그...originalUrl also changes & looks same as the 또, 변경과 외관도 같습니다.url

필요.루트길은 나에게 통한다.

var pool = require('../db');

module.exports.get_plants = function(req, res) {
    // to run a query we can acquire a client from the pool,
    // run a query on the client, and then return the client to the pool
    pool.connect(function(err, client, done) {
        if (err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT * FROM plants', function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            if (err) {
                return console.error('error running query', err);
            }
            console.log('A call to route: %s', req.route.path + '\nRequest type: ' + req.method.toLowerCase());
            res.json(result);
        });
    });
};

실행 후 콘솔에 다음과 같은 내용이 표시되며 브라우저에서 완벽한 결과를 얻을 수 있습니다.

Express server listening on port 3000 in development mode
A call to route: /plants
Request type: get

For those getting 구입하신 분들을 위해undefined부에서req.route.path그것이 맞아요.그것이 맞아요.

루트 핸들러 안에 루트가 있어요미들웨어 핸들러 내부에는 경로가 없습니다.

언급URL : https://stackoverflow.com/questions/12525928/how-to-get-request-path-with-express-req-object

반응형