javascript - 检查变量是否为空不起作用 | NodeJS、Express

标签 javascript node.js express

我正在尝试构建一个博客 API,现在我的架构中有三个字段:

const PostSchema = new Schema({
  timestamp: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    required: [true, "Title is required"]
  },
  content: {
    type: String,
    required: [true, "Content is required"]
  }
})

我还有 createPost 函数,它应该创建一个帖子(没有狗屎):

// Create post
const createPost = (req, res, next) => {
  const title = req.body.title
  const content = req.body.content

  console.log('body', req.body) // getting output

  if (!title) {
    res.status(422).json({ error: "Titel saknas!!!" })
  }

  if (!content) {
    res.status(422).json({ error: "Skriv något för fan!" })
  }

  const post = new Post({
    title,
    content
  })

  post.save((err, post) => {
    if (err) {
      res.status(500).json({ err })
    }
      res.status(201).json({ post })
  })
}

我有这两个 if 语句来检查标题或内容是否为空,但这不起作用。我尝试使用 Postman 发送 POST 请求: enter image description here

但错误表明我的 title 丢失了。但我正在传递我的标题 key 。 enter image description here

所以我想知道为什么这不起作用,感觉像是一些显而易见的东西,但我就是无法让它发挥作用。

感谢您的阅读。

最佳答案

我不太了解 Postman,但我猜测将正文内容类型设置为 raw 会将正文上传为 text/plain,这意味着 body-parser 不会以任何方式解析它(console.log('body', typeof req.body) 将显示“body string”)。

相反,请尝试将内容类型设置为 application/json(并确保您的服务器使用 body-parser 中的 JSON 中间件)。

关于javascript - 检查变量是否为空不起作用 | NodeJS、Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998847/

相关文章:

javascript - javascript for循环中的异步函数

node.js - `RSV2 and RSV3 must be clear` 中的错误 `ws`

javascript - Express JS 无法放置/删除

javascript - 如何从 geojson 设置传单标记的颜色

javascript - Node + Json 验证键嵌套数组

Node .js。获取 HTTP 查询的时间

node.js:构建 msnodesql 失败

javascript - 用 css 交替 div 线分隔符

javascript - 文档上的 JQuery 触发事件性能

javascript - jQuery/Ajax : run alert() as the page/datatable starts to load