0

I want an endpoint that is a GET method to /book with a query parameter called name. If the name is 'scott', I want to return "Cracking the Coding Interview," but if it's 'SCOTT,' I want to do the same thing. Why does this not work?

app.get('/book', function (req, res) {
  let result = ''
  const name = req.query.name.toString().toLowerCase()
  if (name === "scott") {
    result = "Cracking the Coding Interview"
  } else if (name === "enoch") {
    result = "The Pragmatic Programmer"
  } else {
    result = "Good Old Neon"
  }
  res.send(result);
});
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • You should find out what the value of `name` is. – James Jun 02 '22 at 20:43
  • The code looks okay, you should log req.query.name to check if it's coming a good request. – Cesare Polonara Jun 02 '22 at 20:45
  • Use `console.log(name)` to see what it is. – Barmar Jun 02 '22 at 20:51
  • @Barmar unfortunately, I cannot even connect to the server because ndex.ts:12:16 - error TS2532: Object is possibly 'undefined'. 12 const name = req.query.name.toString().toLowerCase() ~~~~~~~~~~~~~~ – Real Analysis Noob Jun 02 '22 at 20:53
  • I don't know Express well, but I suspect you haven't loaded the proper middleware. – Barmar Jun 02 '22 at 20:55
  • @James It's a string but I get this error – Real Analysis Noob Jun 02 '22 at 20:57
  • TSError: ⨯ Unable to compile TypeScript: index.ts:12:16 - error TS2532: Object is possibly 'undefined'. 12 const name = req.query.name.toString().toLowerCase() ~~~~~~~~~~~~~~ – Real Analysis Noob Jun 02 '22 at 20:57
  • Oh it's typescript, you should flag the question as such. Basically typescript is saying that 'req.query.name' could be undefined (for example there is no ?name parameter in the url), and you can't call .toString on undefined. Check https://stackoverflow.com/questions/54884488/how-can-i-solve-the-error-ts2532-object-is-possibly-undefined – James Jun 02 '22 at 21:21

1 Answers1

0

req.query.name could be undefined, and so we must unwrap it to access that value; search up "swift optionals" if this terminology is confusing.