208

次の Express 関数では、次のようになります。

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

reqととは何resですか? それらは何を表し、何を意味し、何をするのでしょうか?

ありがとう!

4

3 に答える 3

309

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(たとえば、 string/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);
});
于 2011-01-14T21:48:11.870 に答える
26

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

また、POSTされたformdataでもbodyparser(app.use(express.bodyParser());)を使用するようにexpressを構成した場合。(POSTクエリパラメータを取得する方法を参照してください?

于 2012-02-02T18:46:50.623 に答える
6

リクエストとレスポンス。

を理解するにはreq、 を試してみてくださいconsole.log(req);

于 2011-01-14T21:47:58.410 に答える