4

I am making a front using Express. I have a table where each row has a link that makes a GET request, so that the back-end (done with node.js) returns a file corresponding to that row. All links make the url GET request like "/documents/table/file". What I intend to do is for my express server to be able to know which link of what row makes the GET request with the req field of it in order to be able to return the corresponding requested file.

The request is being handled in my express server as follows:

router.get('/documents/table/file', async (req, res) =>{
  //Get which element made the get petition
});

As I said before, I intend to know what link from which row of the table performs a request using the req field.

chrs
  • 5,906
  • 10
  • 43
  • 74

3 Answers3

1

The short version is: you can't know this.

The way this is normally handled that if a request is needed for a specific item (or row in a table), you need to add some relevant information to the url that can identify it yourself.

So if it's a GET request for /foo/get-file, and every 'file' has some kind of unique id, you might want to change your url to /foo/get-file/123 or /foo/get-file?id=123

Evert
  • 93,428
  • 18
  • 118
  • 189
1

You need to pass the information about the row/item that makes the GET request, that is a must.

Now with Express there are a couple of ways to do this: Express routing.

1. Defining route params: req.params

GET Request: /documents/table/file/345 (345 is the row identifier name or id etc)

At nodejs express end:

router.get("/documents/table/file/:id", (req, res) => {
  /*request parameter with this kind of route sits in req.params*/
  console.log(req.params);
  const requestedId = req.params.id;
});

2. Sending as query string parameters: req.query

GET Request: /documents/table/file?id=345

At nodejs express end:

router.get("/documents/table/file/", (req, res) => {
  /*request parameter with this kind of route sits in req.query*/
  console.log(req.query);
  const requestedId = req.query.id;
});
ambianBeing
  • 3,449
  • 2
  • 14
  • 25
0

Do you want to access specific file using get command? If so, here's an answer - Express router - :id?.

More precisely, you write something like router.get('/documents/table/file/:id), and this :id is available in req.params object.