I need to create url for get which is going to accept array, how in node.js/express extract array from request?

后端 未结 8 1100
感情败类
感情败类 2020-12-04 22:01

I need to create url for get which is going to accept array, how in node.js/express extract array from request ? I need to pass array with names which parametes I need to ba

相关标签:
8条回答
  • 2020-12-04 22:23

    Using next code:

    app.use('/', (req, res) => {
        console.log(req.query, typeof req.query.foo, Array.isArray(req.query.foo));
        res.send('done');
    });
    

    On backend, you have two standard approaches. For next requests:

    1. /?foo=1&foo=2
    2. /?foo[]=1&foo[]=2

    your NodeJS backend will receive next query object:

    1. { foo: [ '1', '2' ] } 'object' true
    2. { foo: [ '1', '2' ] } 'object' true

    So, you can choose the way you want to. My recommendation is the second one, why? If you're expect an array and you just pass a single value, then option one will interpret it as a regular value (string) and no an array.

    [I said we have two standards and is not ok, there is no standard for arrays in urls, these are two common ways that exist. Each web server does it in it's own way like Apache, JBoss, Nginx, etc]

    0 讨论(0)
  • 2020-12-04 22:32

    Here use this, '%2C' is the HTML encoding character for a comma.

    jsonToQueryString: function (data) {
       return Object.keys(data).map((key) => {
            if (Array.isArray(data[key])) {
                return encodeURIComponent(`${key}=${data[key].map((item) => item).join('%2C')}`);
            }
            return encodeURIComponent(`${key}=${data[key]}`);
        }).join('&');
    }
    

    To access the query params

    const names = decodeURIComponent(req.query.query_param_name);
    const resultSplit = names.split(',');
    
    0 讨论(0)
  • 2020-12-04 22:33

    You can pass array elements separated by slashes - GET /api/person/foo/bar/...

    Define your route as '/api/person/(:arr)*'

    req.params.arr will have the first parameter. req.params[0] will have the rest as string. You split and create an array with these two.

    app.get('/api/person/(:arr)*', function(req, res) {
            var params = [req.params.arr].concat(req.params[0].split('/').slice(1));
            ...
    });
    
    GET /api/person/foo
    params = ["foo"]
    
    GET /api/person/foo/bar
    params = ["foo", "bar"]
    

    ...

    0 讨论(0)
  • 2020-12-04 22:37

    Express has a tool to check if your path will match the route you are creating : Express.js route tester.

    As Jose Mato says you have to decide how to structure your url:

    1. ?foo=1&foo=2
    2. ?foo[]=1&foo[]=2

    The http request should look like this, if you chose method 1:

    http://baseurl/api/?foo=1&foo=2

    Your route should have this logic:

    app.get('/api/:person', (req, res) => {
        /*This will create an object that you can iterate over.*/
        for (let foo of req.params.foo) {
          /*Do some logic here*/
        }
    });
    
    0 讨论(0)
  • 2020-12-04 22:40

    One option is using a JSON format.

    http://server/url?array=["foo","bar"]
    

    Server side

    var arr = JSON.parse(req.query.array);
    

    Or your own format

    http://server/url?array=foo,bar
    

    Server side

    var arr = req.query.array.split(',');
    
    0 讨论(0)
  • 2020-12-04 22:44

    You can encode an array in percent encoding just "overwriting" a field, formally concatenating the values.

    app.get('/test', function(req,res){
        console.log(req.query.array);
        res.send(200);
    });
    
    
    
    
    localhost:3000/test?array=a&array=b&array=c
    

    This query will print ['a','b','c'].

    0 讨论(0)
提交回复
热议问题