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.

Expressのルーティング

Posted at

これは何?

この記事はNode.jsのフレームワークのexpressのルーティングの自分がよく使う物を公式から抜粋したメモです。

基本的なルーティング

app.METHOD(PATH, HANDLER)

例:

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.post('/', (req, res) => {
  res.send('Got a POST request');
});

app.put('/target', (req, res) => {
  res.send('Got a PUT request at /target');
});

app.delete('/target', (req, res) => {
  res.send('Got a DELETE request at /target');
});

ルート・パス

正規表現などで引っかかっているパスにアクセスすることができる。(リクエストを実行できるエンドポイントを定義することができる)

例:

app.get('/random.text', (req, res) => {
  res.send('random.text')
})

app.get('/ab*cd', (req, res) => {
  res.send('ab*cd')
})

app.get(/a/, (req, res) => {
    res.send('(Regular expression) path with "a"')
})

app.get(/.*fly$/, (req, res) => {
  res.send('(Regular expression) /.*fly$/')
})

ルート・パラメータ

パスからパラメータ("key":"value")を取得ができる

app.get('/key1/:value1/key2/:value2', (req, res) => {
  res.send(req.params)
})

例:

ルート・パス: /flights/:from-:to
リクエストURL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }

参考資料:

Express公式

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?