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

前端 未结 26 3494
庸人自扰
庸人自扰 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:02

    So, there are two ways in which this "id" can be received: 1) using params: the code params will look something like : Say we have an array,

    const courses = [{
        id: 1,
        name: 'Mathematics'
    },
    {
        id: 2,
        name: 'History'
    }
    ];
    

    Then for params we can do something like:

    app.get('/api/posts/:id',(req,res)=>{
        const course = courses.find(o=>o.id == (req.params.id))
        res.send(course);
    });
    

    2) Another method is to use query parameters. so the url will look something like ".....\api\xyz?id=1" where "?id=1" is the query part. In this case we can do something like:

    app.get('/api/posts',(req,res)=>{
        const course = courses.find(o=>o.id == (req.query.id))
        res.send(course);
    });
    

提交回复
热议问题