Basic Node and Express - Get Query Parameter Input from the Client

Hey what is wrong with my code

app.route('/name')
  .get((req, res) => {
    const firstName = req.query.first;
    const lastName = req.query.last;

    if (!firstName || !lastName) {
      return res.status(400).json({ error: 'Both first and last names are required.' });
    }

    let fullName;

    // Check for specific test cases
    if (firstName === 'Mick' && lastName === 'Jagger') {
      fullName = 'Mick Jagger';
    } else if (firstName === 'Keith' && lastName === 'Richards') {
      fullName = 'Keith Richards';
    } else {
      // If not a test case, concatenate the provided names
      fullName = `${firstName} ${lastName}`;
    }

    res.json({ name: fullName });
  })
  .post((req, res) => {
    const firstName = req.body.first;
    const lastName = req.body.last;

    if (!firstName || !lastName) {
      return res.status(400).json({ error: 'Both first and last names are required.' });
    }

    const fullName = `${firstName} ${lastName}`;
    res.json({ name: fullName });
  });

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

Basic Node and Express - Get Query Parameter Input from the Client

  • what error are you getting?!

also share that “repl” link for this project as well, thanks and happy coding :slight_smile:

Hi I have noticed . You have tried to use the method chaining. I found the following post on freeCodeCamp forum. It refers to the following link [Express 4.x - API Reference](https://Express method chaining).
The chained methods should be as follows.

I realize you want to return an error if req.query object is undefined. But rather try use a plain get request.

app.get('/name',(req,res)=>{
  const {first,last} = req.query
  res.json({
    first:first,
    last:last
  })
})

Your code is passing for me. Please post all your code, preferably in a Replit.


As an aside. In the GET handler, why are you checking the values and then hardcoding the values based on the values? That makes no sense. Whatever firstName and lastName is should be the response. Just do what you are doing in the else, the conditions are pointless.

Sorry I missed the part where the return JSON Object should contain name property and not first and last separately.

app.get('/name',(req,res)=>{
  const {first,last} = req.query
  res.json({
    name:first + " " +  last,
  })
})

Passes the test for Basic Node and Express - Get Query Parameter Input from the Client

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.