在NodeJS中如何从URL传递参数的方式

环境

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

代码

const express = require('express');
const app = express();

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

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

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

路径变量

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的学生编号这样的个人编号,并且它被保存在数据库中,那么可以使用该编号从数据库中读取信息,以便处理更多的信息。

参数

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之外,还传递了该国为日本。

多个参数

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

可以传递这样多种信息

实例1

image.png

军在这个用户的项目中的路径是c0e625ad8b189237c0b0。

可以读取到像 /:user_name/items/:items_id 这样的设置。

实例2

image.png

可以读取到参数为q=こんにちくわ。

从不同的故事中解释这个观点:实例 ③

image.png

总结

路径变量 → 数据库ID、用户名等唯一信息
参数 → 搜索内容、条件等附加信息

bannerAds