HTTP Requests with express the why does the queries are undefined?

Issue

I’m trying to use express HTTP get requests but for some reason req.query.page is always undefined, What am I doing wrong?

The address for the API is http://localhost:3232/api/tickets?(pageNum)

import express from 'express';
import { tempData} from './temp-data';
import { serverAPIPort, APIPath, staticsPort } from '@fed-exam/config';

console.log('starting server', { serverAPIPort, APIPath });


const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const PAGE_SIZE = 20;
var PAGE_AMOUNT:number = tempData.length % PAGE_SIZE;

app.use((_, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader('Access-Control-Allow-Headers', '*');
  next();
});


app.get(APIPath, (req, res) => {

  // @ts-ignore
  let page: number = req.query.page || 1;

  let paginatedData = tempData.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  console.log("Page " + page + " requested!");

  res.send(paginatedData);
});

app.listen(serverAPIPort);
console.log('server running', serverAPIPort)

Solution

for your queries you would need to follow the structure of ?page=${pageNum} and any additional queries are appended with an & so for example page=${pageNum}&limit=${limit}

Answered By – richardsefton

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published