【问题标题】:Recursively call post method in Node JS在 Node JS 中递归调用 post 方法
【发布时间】:2020-07-30 12:46:48
【问题描述】:

如果错误是重复键,我想再次调用 post 方法。有什么解决方法吗? Id 是使用 Math.Random() 自动生成的。 如果 Error 是重复键即 E11000 则应重新执行 post 方法以生成新的 id 并将其存储在数据库中。

const newRequestIndividualRouter = express.Router();
newRequestIndividualRouter.use(bodyParser.json());

newRequestIndividualRouter.route('/')
.post(checkAuth,(req,res,next) => { //POST METHOD
    req.body.id = Math.floor(Math.random() * 10000000)+100000; //GENERATING ID
    NewRequestIndividual.create(req.body)
    .then((request) => {
        res.statusCode = 200;
        res.setHeader('Content-Type','application/json')
        res.json(request);
    },(err) => {
        
        if(err.code === 11000) {
            **** CALL POST METHOD AGAIN ****
        }
        next(err)
    })
    .catch((err) => {
        next(err)
    });
})

【问题讨论】:

    标签: node.js rest express


    【解决方案1】:

    Math.random() 会根据当前时间自动播种

    你需要一个好的伪随机数生成器

    试试http://davidbau.com/seedrandom

    【讨论】:

      【解决方案2】:

      您可以使用 uuid 代替 Math.random()。 链接-https://www.npmjs.com/package/uuid

      【讨论】:

        猜你喜欢
        • 2015-08-04
        • 2019-02-19
        • 1970-01-01
        • 2019-01-01
        • 2016-12-26
        • 2023-04-10
        • 1970-01-01
        相关资源
        最近更新 更多