Express関数の「RES」および「REQ」パラメーターとは何ですか?

StackOverflow https://stackoverflow.com/questions/4696283

  •  11-10-2019
  •  | 
  •  

質問

次の明示的な関数で:

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

何ですか reqres?彼らは何を表し、彼らは何を意味し、彼らは何をしますか?

ありがとう!

役に立ちましたか?

解決

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の回答に1つのエラーがありました(おそらく最近の変更ですか?):クエリ文字列パラメーターはにあります 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);
});

そして、あなたがそのbodyparserを使用するようにExpressを構成した場合(app.use(express.bodyParser());)また、Post 'ed formdataを使用します。 (見る ポストクエリパラメーターを取得する方法は? )

リクエストと応答。

を理解する req, 、 試してみる console.log(req);.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top