How to get GET (query string) variables in Express.js on Node.js?

前端 未结 26 3562
庸人自扰
庸人自扰 2020-11-21 23:53

Can we get the variables in the query string in Node.js just like we get them in $_GET in PHP?

I know that in Node.js we can get the URL in the request.

26条回答
  •  故里飘歌
    2020-11-22 00:04

    If you are using ES6 and Express, try this destructuring approach:

    const {id, since, fields, anotherField} = request.query;
    

    In context:

    const express = require('express');
    const app = express();
    
    app.get('/', function(req, res){
       const {id, since, fields, anotherField} = req.query;
    });
    
    app.listen(3000);
    

    You can use default values with destructuring too:

    // sample request for testing
    const req = {
      query: {
        id: '123',
        fields: ['a', 'b', 'c']
      }
    }
    
    const {
      id,
      since = new Date().toString(),
      fields = ['x'],
      anotherField = 'default'
    } = req.query;
    
    console.log(id, since, fields, anotherField)

提交回复
热议问题