How to pass an object to a GET request?

Hi I'm currently trying to pass an object to a GET request for search filter in nodejs using express but I get a return of 404 GET /route1/search/[object%20Object] 404 1.148 ms - 38

I already try to log the result in the terminal using console.log(req.params.dataObject); or console.log(req.params.dataObject.option); but get the result of [Object, Object] or Undefined

router.get('/search/:dataObject',
 async function (req, res) {
    try {
      console.log(req.params.dataObject);
      res.status(200).json(searchPhone);
    } catch (err) {
      return res.status(404).json({
        error: err.message
      });
    }
  });

I expect the result to be {option: 'some data', keyword: 'some data'}

Upvotes: 1

Views: 2559

Answers (1)

Brad
Brad

Reputation: 163262

You can't shove an object into a URL without encoding it somehow. Whatever code is calling your server is attempting to do that, and JavaScript is converting the object to a string, which is where the [object Object] comes from. This happens before your server ever gets to it.

What you should probably be doing instead is using the querystring. This is a standard way for you pass in key/value parameters. For example, your client would call:

GET /search?option=some%20data&keyword=some%20data

Then in your server, you could use:

req.query.option
req.query.keyword

Upvotes: 3

Related Questions