【问题标题】:How to use fastify to send multiple URL parameters?如何使用 fastify 发送多个 URL 参数?
【发布时间】:2020-04-20 07:07:39
【问题描述】:

我已经使用 fastify 声明路由如下:

const apiService = require('./apiService');

try {
    server.get('/api/status/*', apiService);
} catch (err) {
    console.log(err);
    process.exit(1);
}

我的api服务定义如下:

async function entryFunc(request, response) {
    try {
        console.log("Params are ");
        console.log(request.params);
    } catch (err) {
        console.log(err);
    }
}

我在调用 api http://localhost:3002/api/status/1/2 时得到以下输出:

Params are:
{ '*': '1/2' }

网址可以有infinite number of parth params,这就是我在路由中使用wildcard的原因

我想修改entryFunc(request, response),以便将值12 存储在一个数组中,当我打印array[0] 时,我应该得到1 的值

【问题讨论】:

    标签: node.js node-modules fastify


    【解决方案1】:

    Fasify 使用find-my-way 作为路由器并支持所有这些功能。

    如果你总是有 2 个路径参数,你应该将你的路由定义为:

    server.get('/api/status/:one/:two', apiService);
    

    然后你的params 会是这样的:

    // /api/status/hello/world
    {
      "one": "hello",
      "two": "world"
    }
    

    您可以简单地通过Object.values(request.params) // ["hello", "world"]request.params['*'].split('/') 转换为数组

    【讨论】:

    • url 可以有无限数量的部分参数,这就是我在路由中使用通配符的原因
    • 我在使用Object.values(request.params) 时收到[ '1/2' ]。如何将其转换为数组为['1','2'] ??
    • request.params['*'].split('/')
    • /api/status/:one&:two的情况如何?这将如何运作?
    • 什么意思?
    猜你喜欢
    • 2019-09-16
    • 2019-10-06
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多