如何在 npm 中查找数组元素?

How to find array elements in npm?

我正在尝试从该用户虚拟数组中查找具有输入的电子邮件和密码的用户,但我在 return 值中未定义,因此我无法登录。如果我在控制台中 运行 此代码,它会获取正确的输出。有人可以帮助为什么这个查找功能(在 post 请求中)在 Node 中不起作用吗?

虚拟数组 -

const users = [
            { id: 1, name: 'Sherry', email:'sherry@gmail.com', password: 1234 },   
            { id: 2, name: 'harry', email:'harry@gmail.com', password: 1234 },
            { id: 3, name: 'cherry', email:'cherry@gmail.com', password: 1234 }
        ]

获取请求 -

app.get('/login', (req, res) => {
        res.send(`<form method='POST' action='/login'>
            <input type="email" name="email" placeholder="Enter email" />
            <input type="password" name="password" placeholder="Enter pass" />
            <input type="submit" />
        </form>`);
    })

Post请求-

app.post('/login', (req,res) => {
        const { email, password } = req.body;
        console.log(email)
        console.log(password)
        console.log(users)
        let user1 = users.find((user) => user.email === email && user.password === password);
        console.log(user1);
    
        if(user1) {
                req.session.userId = user.id
                return res.redirect('/home')
        }
    
        res.redirect('/')
    })

问题 - User1 未定义。

我会说 req.body 中收到的 password 值是 string 。您的 === 比较器还会检查变量 type,并且 stringnumber 将不匹配。

选项 1

我建议将您的用户数据 password 属性更改为 string:

const users = [
  { id: 1, name: 'Sherry', email:'sherry@gmail.com', password: '1234' },   
  { id: 2, name: 'harry', email:'harry@gmail.com', password: '1234' },
  { id: 3, name: 'cherry', email:'cherry@gmail.com', password: '1234' }
]

选项 2

如果您只想使用数字密码,您还可以更改 find 函数以正确比较数字:

let user1 = users.find((user) => user.email === email && user.password === parseInt(password));

如果有效请告诉我。

// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());

// Parse JSON bodies (as sent by API clients)
app.use(express.json());

这两行将确保您的服务器端将从 req.body 接收数据。 首先,您将数据作为表单数据发送,因此您需要包含

// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());

这将允许您读取来自 req.body 的数据。

    app.post('/login', (req,res) => {
    const { email, password } = req.body;
    console.log('req',req.body)
    console.log("email",email)
    console.log("password",password)
    let index = users.findIndex((user) => user.email === email  && user.password == password);
    console.log("index",index)
    let user1= users[index]
    console.log("user1",user1);

    if(user1) {
        console.log("HERE=======================")
            req.session.userId = user1.id
            return res.redirect('/home')
    }

    res.redirect('/')
})

现在试试上面的代码snap,希望对你有帮助。