繁体   English   中英

检查express.js中的Param是否为空

[英]Check if Param is empty or not in express.js

我想创建一个表并将其放在不像这样的参数中为空的所有参数上

http://localhost:5002/5u3k0HRYqYEyToBB53m1=Test2@test.fr&m2=test3@test.com&m3=&m4=&m5=&m6=&m7=&m8=&m9=test6@test.com&m10=&m11=test10@test.com&m12=&m13=&m14=&m15=&m16=&m17=&m18=&m19=&v=4.1.2&hw=6

之后,我想将所有电子邮件(m1,m2,m9,m11)存储在一个表中。

console.log(b) // test2@test.fr , test3@test.com , test10@test.com , test6@test.com

所以我做到了

    let emailTable = [req.query.m0,req.query.m1,req.query.m2......]
Box.push({Email:emailTable}}
console.log(Box)// it show me even the empty param, i want only the full one 

这是问题JSFIDLE的简单解决方案: https ://jsfiddle.net/85bzj3a3/7/

// Lets imagine this object is your req.param
reqParam = {
  m1: 'email1',
  m2: '',
  m3: 'email3',
  m4: 'email4',
  someOther1: 'some other param',
  m5: '',
  m61: 'email6',
  someOther: 'otherValue'
}

const  emailTable = []
for (let key of Object.keys(reqParam)){
    // check if it is email and if it has value
  if(key.match(/^[m]+[0-9]*$/g) != null && reqParam[key] != ''){
    emailTable.push(reqParam[key])
  } 
}
console.log(emailTable)

我所做的就是检查参数,使用正则表达式检查它是否为email参数,然后检查它是否具有值,如果有,则将其推送到emailTable。

我认为在推送到数组时对所有参数进行硬编码是不明智的,因为下次您在url中添加另一个参数时,您必须在函数中再次对其进行硬编码,这不是bueno。

这是我为您解决的问题。 我正在使用lodash使事情更容易阅读。 这个问题的本地实现应该很容易弄清楚。 我的index.js文件包含非常简单的Express服务器,可以将查询字符串参数打印到控制台。 让我知道您是否还有问题。

// Request URL: http://localhost/?&m1=Has%20value&m2=&m3=&m4=test@mail.com

const express = require('express');
const app = express();
const _ = require('lodash');

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

    const params = _.values(req.query);

    console.log(params); // [ 'Has value', '', '', 'test@mail.com' ]

    const withValues = _.filter(params, p => !!p);

    console.log(withValues); // [ 'Has value', 'test@mail.com' ]

    res.sendStatus(200);

});

app.listen(80);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM