5

I'm new to node and express and I would appreciate any help. I'm trying to write a get request which checks if the req.params.address_line is empty and does something if it is, but can't seem to figure out how to do that. So far I have tried this:

app.get('/smth/smth_else/:address_line', function(req, res){
  if(req.params.address_line===""){
    res.send("Hello World.")
  }
}

This isn't working though so I don't think it is correct. How can I check if the address_line is empty? I googled it extensively, but can't find a working solution. Thanks!

1
  • 1
    I guess you're looking for an optional path parameter, try: /smth/smth_else/:address_line? (note the ? at the end). Commented Oct 1, 2021 at 18:47

4 Answers 4

11

You'll have to check first if the whole req.params exists or not

Like this

app.get('/smth/smth_else/:address_line', function(req, res){

  if(!req.params)
    return res.send("NO PARAMS PASSED")

  if(!req.params.address_line)
    return res.send("NO address_line PASSED")

  if(req.params.address_line === ""){
    res.send("ADDRESS LINE EMPTY.")
  } else {
    res.send("ADDRESS LINE > ",req.params.address_line)
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

GET /smth/smth_else would result in a 404. Thus this request handler will only trigger res.send("ADDRESS LINE > ",req.params.address_line)
6

A potential option is to write a middleware that could create a nice reusable interface for requiring parameters like so:

const requireParams = params => (req, res, next) => {
    const reqParamList = Object.keys(req.params);
    const hasAllRequiredParams = params.every(param =>
        reqParamList.includes(param)
    );
    if (!hasAllRequiredParams)
        return res
            .status(400)
            .send(
                `The following parameters are all required for this route: ${params.join(", ")}`
            );

    next();
};

app.get("/some-route", requireParams(["address_line", "zipcode"]), (req, res) => {
    const { address_line, zipcode } = req.params;
    if (address_line === "") return res.status(400).send("`address_line` must not be an empty string");


    // continue your normal request processing...
});

This example makes use of express middlewares and Array.prototype.every(). If you are unfamiliar, these links will provide the relevant documentation for how this works.

Comments

2

You can use a simple falsy check !req.params.address_line for when it is an empty string "", false, null, undefined, 0, or NaN.

1 Comment

It's important to be careful with just checking for falsey values if 0 is a valid value for the parameter. It might be better to explicitly check for param === undefined
1

There are two cases, you need to handle

For unique route names

app.get('/smth/smth_else/:address_line', function(req, res){
  if(!req.params){
     res.send("Params Empty!")
  }
}

For duplicate route names and multiple params

app.get('/smth/smth_else/:address_line1/:address_line2', function(req, res){
  if(Object.keys(req.params).length === 0){
     res.send("Params Empty")
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.