0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Express4系でのreq.paramsの値の取得

Last updated at Posted at 2020-05-19

Express3系のやり方

『現場で通用する力を身につけるNode.jsの教科書』にも記載のあるやり方です。/index/12/taro等でブラウズした際にid=12,name='taro'で値を取得したい場面です。日本語で説明のあるサイトを探しましたが見つからず、ネタ帳がわりにここに記します。

app.js
var routes = require('./routes');

app.get('/', routes.index);
//次の3行を追加 
app.get('/index', routes.index);
app.get('/index/:id', routes.index);
app.get('/index/:id/:name', routes.index);
index.js
exports.index = function(req,res){
  var id = req.params.id;
  var name = req.params.name
  //id,nameを使って様々な処理
}

これが2020年5月19日現在でガラッと変わってしまっています。app.getが使えなくなってしまいました。

Express4系での方法

スタート地点のコード

Expressプロジェクト作成時点でのコードの一部です。

app.js
var indexRouter = require('./routes/index');

app.use('/', indexRouter);
index.js
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Routerオブジェクトが新しく追加されましたが、何となく以前と似た経路を辿りそうです。

パラメーターの追加方法

前のバージョンではapp.jsに'./index/:id'などを加えていましたが、今はindex.jsに加えるとうまくいくみたいです。router.getを何回もコピーして'/'を変えるやり方です。コードの見易さをよくするために中の無名関数に名前をつけます。

index.js
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', func);
router.get('/index', func);
router.get('/index/:id', func);
router.get('/index/:id/:name', func);

function func(req, res, next) {
  var id = req.params.id;
  var name = req.params.name; 
  //id,nameを使って様々な処理
}
module.exports = router;

これで、/index/12でブラウズすればid=12が、/index/12/taroでブラウズすればid=12,name='taro'が取得できるようです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?