【问题标题】:why "if" condition is ignored?为什么“如果”条件被忽略?
【发布时间】:2022-02-15 21:18:16
【问题描述】:

当我在邮递员上运行此服务器时,我得到“错误登录”,但它应该返回“成功”。 但是当我添加console.log(body.req)然后在终端上我得到“名称,电子邮件,密码”,这是我在正文中传递的。 还有当我做console.log(req.body.name===database.users[0].name && req.body.email===database.users[0].email, req.body, database); 然后在终端中,我从数据库中获取所有数据,但对于“If”,它返回 false。

 const bodyParser=require('body-parser');   
 const app=express();
  app.use(bodyParser.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(express.urlencoded({ extended: false}));

 const database= {
     users : [
         {
          id: '123',
          name: 'amit',
          email :'amitrk@gmail.com',
          password:'123',
          entries:'0',
           joined: new Date()
         },
         /*{
            id: '124',
          name:'Rahul',
          email :'amit@gmail.com',
          password:'54858',
          entries:'0',
           joined: new Date() 
         },*/
     ]
     
 }
   /*const app=express();
   app.get('/',(req,res)=>{
        res.send("this is working");
   })*/
    app.post('/signin',(req,res)=>{
         //console.log(req.body);
      if(req.body.name===database.users[0].name && req.body.email===database.users[0].email) {
           console.log("sucess");
      }
       else {
           res.status(400).json("error login");
       }
    })
   app.listen(3000,()=>{
        console.log("app is running on port");
   })

【问题讨论】:

  • 尝试做更多的调试,比如 console.log(req.body.name); console.log(req.body.name===database.users[0].name);等等,看看到底出了什么问题。
  • 如果您的客户端代码以minimal reproducible example 形式调用此路由,我们将无法以任何有用的方式为您提供帮助。
  • 这是我遇到错误的代码,基本上它忽略了“IF”语句并返回我不想要的 else 语句
  • app.post('/signin',(req,res)=>{ //console.log(req.body.name); if(req.body.name===database. users[0].name && req.body.email===database.users[0].email) { console.log("sucess"); } else { res.status(400).json("error login" ); } })
  • 可能是空格。到目前为止,解决此问题的最快方法是使用内置于 IDE 或浏览器中的调试器。 (是的,您可以在 IDE 的调试器中运行 Node.js 代码,甚至可以使用 the devtools of your browser。)从根本上说,字符串不匹配。我们不能告诉你为什么。您的调试器可以。

标签: node.js json server


【解决方案1】:

首先,您似乎没有在 if 条件下发送响应。如果控件进入您的 if 条件,这将在控制台上打印“成功”,但不发送任何响应(即挂起请求)。

其次,这正是您运行的代码吗?您是否在 if 条件中也进行了密码检查?请注意,使用=== 时,'123' 不等于 123。

这些是唯一的线索,我可以从分享的内容中提供。可以分享一下postman request body,可能会有更多线索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 2019-09-11
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-11-06
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多