LoginSignup
1
1

More than 1 year has passed since last update.

nodeJS でURLからパラメータを渡す方法

Posted at

環境

{
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
  },
}

Code

server.js
const express = require('express');
const app = express();

app.get('/qiita', (req, res) => {
    res.send('Hola!')
})

// ここにパラメータを受けるコード

app.listen(8080, function () {
    console.log('listening on 8080')
});

Path Variable(経路変数)

server.js
app.get('/qiita/:name', (req, res) => {
    console.log(req.params.name)
    // Ari 

    res.send(`Hello! ${req.params.id}`)
})

image.png

req.paramsはオブジェクトでわたされ、{ name: 'Ari' }のような形を渡す
ここではAriを経路変数としたが、もしAriの学生番号のような個人の番号があり、それがDBに保存されているのであれば、その番号を用いてDBから情報を読み込むことによってより多くの情報を扱うことができる。

Parameter

server.js
app.get('/qiita/:name', (req, res) => {
    console.log(req.params.name)
    // Ari
    console.log(req.query.country)
    // Japan


    if (req.query.country) {
        res.send(`Hello! ${req.params.name} from ${req.query.country}!`) 
    } else {
        res.send(`Hello! ${req.params.name}!`)
    }
})

image.png

名前がAriであることに加えて、より付加的な情報を渡したい

変数経路がAriであることに加えてその国がJapanであることを渡した。

複数のParameter

server.js
app.get('/qiita/:name', (req, res) => {
    console.log(req.params.name)
    // Ari
    console.log(req.query)
    // { country: 'Japan', age: '25' }

    if (req.query.country && req.query.age ) {
        res.send(`Hello! ${req.params.name}(${req.query.age }) from ${req.query.country}!`)
    } else {
        res.send(`Hello! ${req.params.name}!`)
    }
})

image.png

このような複数の情報を渡すことができる

実例 ①

image.png

junzaiというユーザーのitemc0e625ad8b189237c0b0という経路

/:user_name/items/:items_idのように設定されていることが読み取れる。

実例 ②

image.png

パラメータがq=こんにちくわであることが読み取れる

実例 ③

image.png
新着順で並べ替えた結果、q=こんにちくわsort=createdであることが読み取れた。

まとめ

Path Variable → DBのid, ユーザー名など、ユニークな情報
Parameter → 検索内容、条件など、付加的な情報

1
1
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
1
1