简体   繁体   中英

API queries in Nodejs/Express

why doesn't this work?

/search?name=:name

but this works :

/search/name=:name

how to make the former work with the ? (Question mark)

See https://expressjs.com/en/guide/routing.html

Query strings are not part of the route path.

If you want to use the query string, use req.query :

app.get('/search', function (req, res) {
  console.log(req.query);
});

What you want is either route parameters:

app.get('/foo/:bar', (req, res) => { //GET /foo/helloworld
    console.log(req.params.bar);     //helloworld
    //...
});

Or GET parameters:

app.get('/foo', (req, res) => {  //GET /foo?bar=helloworld
    console.log(req.query.bar);  //helloworld
    //...
});

What you are doing right now is mixing them up, which doesn't work.

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