web-dev-qa-db-ja.com

「?」の後にGETパラメータにアクセスする方法エクスプレスでは?

私はこのようなクエリのパラメータを取得する方法を知っています。

app.get('/sample/:id', routes.sample);

この場合、パラメータを取得するためにreq.params.idを使用できます(例:2/sample/2)。

しかし、/sample/2?color=redのようなURLの場合、どうやって変数colorにアクセスできますか?

私はreq.params.colorを試しましたが、うまくいきませんでした。

446
Hanfei Sun

そのため、 express reference をチェックしたところ、req.query.colorが私が探していた値を返すことがわかりました。

req.paramsはURLに「:」が含まれている項目を表し、req.queryは「?」に関連付けられている項目を表します。

例:

GET /something?color1=red&color2=blue

それからエクスプレスで、ハンドラは:

app.get('/something', (req, res) => {
    req.query.color1 === 'red'  // true
    req.query.color2 === 'blue' // true
})
630
Hanfei Sun

ルートのクエリ文字列パラメータの値を取得するには、req.queryを使用します。 req.query を参照してください。 http:// localhost:3000 /?name = satyam という名前のパラメータで値を取得したい場合、「Get」ルートハンドラは次のようになります。

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});
74
satyam kumar

更新: req.param()は現在廃止予定であるため、今後はこの回答を使用しないでください。


あなたの答えはそれをするのに好ましい方法です、しかし、私はあなたがまたあなたがurl、post、およびrouteパラメータすべてに req.param(parameterName, defaultValue) でアクセスできることを指摘したいと思いました。

あなたの場合:

var color = req.param('color');

エクスプレスガイドより:

検索は次の順序で実行されます。

  • 必須パラメータ
  • 要求者
  • requ.query

ガイドには次のように記載されています。

明確にするために、req.body、req.params、およびreq.queryに直接アクセスすることをお勧めします。ただし、各オブジェクトからの入力を本当に受け入れるのでない限り。

しかし実際には、req.param()が十分明確であることを実際に私は見つけました。そしてある種のリファクタリングをより簡単にします。

63
Zugwalt

@ Zugwaitの答えは正しいです。 req.param()は非推奨です。 req.paramsreq.queryまたはreq.bodyを使うべきです。

しかし、それを明確にするためだけに:

req.paramsはルートの値だけで埋められます。つまり、/users/:idのようなルートがある場合は、req.params.idまたはreq.params['id']のどちらでもidにアクセスできます。

req.queryreq.bodyは、ルートにあるかどうかにかかわらず、 all paramsが入力されます。もちろん、クエリ文字列のパラメータはreq.queryで利用でき、投稿本文のパラメータはreq.bodyで利用できます。

それで、あなたの質問に答える、colorはその道筋にはないので、あなたはそれを得ることができるはずですreq.query.colorまたはreq.query['color']

42
André Pena

クエリ文字列とパラメータが異なります。

両方を単一のルーティングURLで使用する必要があります

下記の例を確認してください。

app.get('/sample/:id', function(req, res) {

 var id = req.params.id; //or use req.param('id')

  ................

});

あなたの2番目のセグメントを通過するためのリンクを取得するあなたのIDの例です: http:// localhost:port/sample/123

あなたが問題に直面しているならば、 '?'を使用して質問ストリングとして変数を渡すことを使ってくださいオペレーター

  app.get('/sample', function(req, res) {

     var id = req.query.id; 

      ................

    });

このようにリンクを張ってください: http:// localhost:port/sample?id = 123

両方とも単一の例で

app.get('/sample/:id', function(req, res) {

 var id = req.params.id; //or use req.param('id')
 var id2 = req.query.id; 
  ................

});

リンクの例を取得します。 http:// localhost:port/sample/123?id = 123

エクスプレスマニュアルは、QueryStringにアクセスするために req.query を使うべきだと言っています。

// Requesting /display/post?size=small
app.get('/display/post', function(req, res, next) {

  var isSmall = req.query.size === 'small'; // > true
  // ...

});
14
Jan Biasi
const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')

const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
  usersNdJobs()
    .then((users) => {
      res.render('users', { users })
    })
    .catch(console.error)
})

app.get('/api/company/users', (req, res) => {
  const companyname = req.query.companyName
  console.log(companyname)
  userByJob(companyname)
    .then((users) => {
      res.render('job', { users })
    }).catch(console.error)
})

app.post('/api/users/add', (req, res) => {
  const userName = req.body.userName
  const jobName = req.body.jobName
  console.log("user name = "+userName+", job name : "+jobName)
  addUser(userName, jobName)
    .then((result) => {
      res.status(200).json(result)
    })
    .catch((error) => {
      res.status(404).json({ 'message': error.toString() })
    })
})
app.post('/users/add', (request, response) => {
  const { userName, job } = request.body
  addTeam(userName, job)
  .then((user) => {
    response.status(200).json({
      "userName": user.name,
      "city": user.job
    })
  .catch((err) => {
    request.status(400).json({"message": err})
  })
})

app.post('/api/user/company/add', (req, res) => {
  const userName = req.body.userName
  const companyName = req.body.companyName
  console.log(userName, companyName)
  addUserToCompany(userName, companyName)
  .then((result) => {
    res.json(result)
  })
  .catch(console.error)
})

app.get('/api/company/user', (req, res) => {
 const companyname = req.query.companyName
 console.log(companyname)
 userByJob(companyname)
 .then((users) => {
   res.render('jobs', { users })
 })
})

app.listen(3000, () =>
  console.log('Example app listening on port 3000!')
)
5
seme

Expressの一部のアプリで使い始めた素敵なテクニックは、Expressのリクエストオブジェクトのクエリ、パラメーター、および本文フィールドをマージするオブジェクトを作成することです。

//./express-data.js
const _ = require("lodash");

class ExpressData {

    /*
    * @param {Object} req - express request object
    */
    constructor (req) {

        //Merge all data passed by the client in the request
        this.props = _.merge(req.body, req.params, req.query);
     }

}

module.exports = ExpressData;

次に、コントローラー本体、またはエクスプレスリクエストチェーンの範囲内の任意の場所で、以下のようなものを使用できます。

//./some-controller.js

const ExpressData = require("./express-data.js");
const router = require("express").Router();


router.get("/:some_id", (req, res) => {

    let props = new ExpressData(req).props;

    //Given the request "/592363122?foo=bar&hello=world"
    //the below would log out 
    // {
    //   some_id: 592363122,
    //   foo: 'bar',
    //   hello: 'world'
    // }
    console.log(props);

    return res.json(props);
});

これにより、ユーザーがリクエストで送信した可能性のあるすべての「カスタムデータ」を「掘り下げる」だけで便利で便利です。

「小道具」フィールドが必要な理由これは切り捨てられたスニペットであるため、多くのAPIでこの手法を使用し、このオブジェクトに認証/承認データも保存します(以下の例を参照)。

/*
 * @param {Object} req - Request response object
*/
class ExpressData {

    /*
    * @param {Object} req - express request object
    */
    constructor (req) {

        //Merge all data passed by the client in the request
        this.props = _.merge(req.body, req.params, req.query);

        //Store reference to the user
        this.user = req.user || null;

        //API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
        //This is used to determine how the user is connecting to the API 
        this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
    }
} 
1
Lee Brindley