简体   繁体   中英

How to use fastify to send multiple URL parameters?

I have declared route using fastify as follows:

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

My api service is defined as follows:

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

I am getting following output when calling api http://localhost:3002/api/status/1/2 :

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

The url can have infinite number of parth params and that is why I am using wildcard in my route

I want to modify entryFunc(request, response) such that the values 1 and 2 are stored in an array and when I print array[0] I should get value as 1

Fasify usesfind-my-way as the router and supports all that functions.

If you have always 2 path params you should define your route as:

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

And then your params will be like:

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

That you can convert to an array simply by Object.values(request.params) // ["hello", "world"] or request.params['*'].split('/')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM