为什么我的API中的此端点返回[]而不是404错误?

我当前正在使用Zeit Now创建一些API,并且当user变量为[](一个空数组)时,我试图实现404错误,但是当我获取此端点时,API也正在发送[]。如何实施?是因为user是一个承诺吗?

const db = require('../../lib/db')
const escape = require('sql-template-strings')

module.exports = async (req,res) => {
  const user = await db.query(escape`
    SELECT *
    FROM users
    WHERE username = ${req.body.username}
    AND password = ${req.body.password}
  `)

  if (user === []) {
    res.status(404).json({ message: 'User with these credentials doesn\'t exist.' })
    return false
  }

  res.status(200).json(user)
}
boh333 回答:为什么我的API中的此端点返回[]而不是404错误?

因为

[] === [] // false

因此您要检查length属性

if (user.length === 0) {
    res.status(404).json({ message: 'User with these credentials doesn\'t exist.' })
    return false
}
本文链接:https://www.f2er.com/2778723.html

大家都在问