最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node ExpressJS | How to pass custom query params validation - Stack Overflow

programmeradmin3浏览0评论

Learning ExpressJS here. I have a get route that expects query params i.e.


app.get('/api', (req, res) => {
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})

On postman the following http://localhost:5000/api?name=Messi&age=31&club=Barcelona

returns 200 with the res.body as:

{
    "name": "Messi",
    "age": "31",
    "club": "Barcelona"
}

Question

How could I write a custom validation where:

  • If the requested query param doesn't exist: status 400
  • If any of the params are missing i.e (name, age, club) return a response saying that whichever missing param (name, age, and/or age) is required

Learning ExpressJS here. I have a get route that expects query params i.e.


app.get('/api', (req, res) => {
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})

On postman the following http://localhost:5000/api?name=Messi&age=31&club=Barcelona

returns 200 with the res.body as:

{
    "name": "Messi",
    "age": "31",
    "club": "Barcelona"
}

Question

How could I write a custom validation where:

  • If the requested query param doesn't exist: status 400
  • If any of the params are missing i.e (name, age, club) return a response saying that whichever missing param (name, age, and/or age) is required
Share Improve this question asked Mar 7, 2019 at 17:06 Null isTrueNull isTrue 1,9168 gold badges30 silver badges50 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

The above answers are correct, but as someone who has worked with scalable and maintenable APIs, I'd remend standardizing the validation process of you API using JSON Schemas to define the expected input, and AJV to validate these schemas.

Example usage:

const Ajv = require('ajv');
const express = require('express');

const app = express();

app.get('/api', (req, res) => {

    // define precisely the expected shape of the request
    const schema = {
        type: 'object',
        properties: {
            name: { type: 'string' },
            age: { type: 'string' },
            club: { type: 'string' }
        },
        required: ['name', 'age', 'club']
    }

    // validate the request
    const ajv = new Ajv();
    const valid = ajv.validate(schema, req.query);
    if(!valid) res.status(400).send(ajv.errors);

    // request is valid. Do whatever
    res.send(req.query);

})

app.listen(8080, () => console.log('Server listening on port 8080'));

Response to /api:

[
    {
        "keyword": "required",
        "dataPath": "",
        "schemaPath": "#/required",
        "params": {
            "missingProperty": "name"
        },
        "message": "should have required property 'name'"
    }
]

Response to /api?name=messi&age=10&club=barcelona:

{
    "name": "messi",
    "age": "10",
    "club": "barcelona"
}

Yes it takes a little bit more code, but trust me, it's the way to go if you want to prepare your app for plex and scalable API validation.

You can build an easy validation middleware.

function validateQuery(fields) {

    return (req, res, next) => {

        for(const field of fields) {
            if(!req.query[field]) { // Field isn't present, end request
                return res
                    .status(400)
                    .send(`${field} is missing`);
            }
        }

        next(); // All fields are present, proceed

    };

}

app.get('/api', validateQuery(['name', 'age', 'club']), (req, res) => {
  // If it reaches here, you can be sure that all the fields are not empty.
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})

You can also use a third party module for validating requests.

  • Express Validator
  • Express Superstruct (I'm the author)

You need to check value of every params value

If(typeof req.query.name == 'undefined' )
 { res.status(400).send('name is missing') }

Check for every value

发布评论

评论列表(0)

  1. 暂无评论