🎓 A1Learner
🔍
0 of 50 lessons completed

Query Strings

A query string is the part of an address after a question mark. It carries small named values with a request.

A route that reads a query

This route answers /search and reads the value q.

app.get('/search', (req, res) => {
  res.send('You searched for ' + req.query.q);
});

Read one value

This line reads the value for the name q.

console.log(req.query.q);

Example

const express = require('express');

const app = express();

app.get('/search', (req, res) => {
  res.send('You searched for ' + req.query.q);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Key points

  • A query string starts with a question mark.
  • It carries pairs of names and values, like q=nodejs.
  • The & sign joins two pairs, as in q=nodejs&lang=en.
  • req.query holds the values from the query string.
  • req.query.q holds the value for the name q.
  • If a name is missing, the value is undefined.

In this example, the route answers the address /search. A visit to /search?q=nodejs carries the value nodejs for q. The server answers You searched for nodejs. The startup line prints Server running on port 3000.

Note

A query string is part of the address, not part of the route.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A visit opens /search?q=nodejs. What does req.query.q hold?