programing

Express 기능에서 "res" 및 "req" 매개 변수는 무엇입니까?

oldcodes 2023. 5. 29. 11:08
반응형

Express 기능에서 "res" 및 "req" 매개 변수는 무엇입니까?

다음 Express 기능의 경우:

app.get('/user/:id', function(req, res){
    res.send('user' + req.params.id);
});

무엇이req그리고.res그들은 무엇을 의미하며 무엇을 의미합니까?

감사합니다!

req는 이벤트를 발생시킨 HTTP 요청에 대한 정보를 포함하는 개체입니다.에 대응하여req당신이 사용하는res원하는 HTTP 응답을 다시 보냅니다.

이러한 매개 변수는 원하는 이름으로 지정할 수 있습니다.더 명확한 경우 코드를 다음과 같이 변경할 수 있습니다.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

편집:

다음과 같은 방법이 있다고 가정합니다.

app.get('/people.json', function(request, response) { });

요청은 다음과 같은 속성을 가진 개체가 됩니다(몇 가지 예를 들면).

  • request.url어느 쪽인가 하면"/people.json"이 특정 작업이 트리거될 때
  • request.method어느 쪽인가 하면"GET"이 경우, 그러므로.app.get()불러.
  • 의 HTTP 헤더 배열request.headers다음과 같은 항목 포함request.headers.accept요청한 브라우저 종류, 처리할 수 있는 응답 종류, HTTP 압축을 이해할 수 있는지 여부 등을 결정하는 데 사용할 수 있습니다.
  • 쿼리 문자열 매개 변수 배열(있는 경우)request.query(예:/people.json?foo=bar결과적으로request.query.foo문자열 포함"bar").

이 요청에 응답하려면 응답 개체를 사용하여 응답을 작성합니다.에서 확장하려면people.json예:

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the data is fetched from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

Dave Ward의 답변에서 한 가지 오류를 발견했습니다(아마도 최근에 변경된 내용인가요?).쿼리 문자열 매개 변수는 다음과 같습니다.request.query,것은 아니다.request.params(https://stackoverflow.com/a/6913287/166530 참조)

request.params기본적으로 경로의 "구성요소 일치" 값으로 채워집니다.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

그리고, 본문 파서를 사용하도록 express를 구성한 경우(app.use(express.bodyParser());) 또한 POST'ed 폼 데이터를 포함합니다.(POST 쿼리 매개 변수를 검색하는 방법을 참조하십시오.)

요청 및 응답.

이해하기 위해req을 시험해 보다console.log(req);.

언급URL : https://stackoverflow.com/questions/4696283/what-are-res-and-req-parameters-in-express-functions

반응형