【问题标题】:If request body is exist it should give me 409如果请求正文存在,它应该给我 409
【发布时间】:2022-01-31 04:25:35
【问题描述】:

*请任何人帮助,如果名称存在于 NodeJS express 中,我会尽量避免该请求 *

这是我的代码


/* Post new person to persons */
app.post("/api/persons/", (req, res) => {
  const schema = {
    name: Joi.string().alphanum().min(3).max(30).required(),
    number: Joi.string().min(9).max(30).required(),
  };
  const { error } = validateFunction(req.body);
  const { body } = req;
  const reqValue = persons.some(
    (person) => person.name.toLowerCase() === body.name.toLowerCase()
  );
  if (error) return res.status(400).send(error.details[0].message);
  else if (reqValue)
    return res.status(409).send(`${body.name} is already exist`);
  else {
    const person = {
      id: persons.length + 1,
      name: req.body.name,
      number: req.body.number,
    };

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

我解决了这个问题:

/* Post new person to persons */
app.post("/api/persons/", (req, res) => {
    const schema = {
        name: Joi.string().exist().alphanum().min(3).max(30).required(),
        number: Joi.string().min(9).max(30).required(),
    };
    const { body } = req;
    const { error } = validateFunction(body, schema);
    const result = persons.filter(({ name }) => name === body.name);

    console.log("resulit", result);
    console.log("The name of request", body.name);

    if (error) return res.status(400).send(error.details[0].message);
    else if (result && result.length > 0) return res.status(409).send(`${body.name} is already exist`);
    else {
        const person = {
            id: persons.length + 1,
            name: req.body.name,
            number: req.body.number,
        };
        persons.concat(person);
        res.send(person);
    }
});

【讨论】:

  • 您的答案可以通过添加有关代码的作用以及它如何帮助您的更多信息来改进。
猜你喜欢
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 2021-12-11
  • 2017-03-10
  • 2021-09-09
  • 1970-01-01
相关资源
最近更新 更多