2017-09-01 75 views
1

我想建立一个博客API,而现在我已经在我的架构三个方面:检查变量是否为空不工作|的NodeJS,快速

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丢失。但我传递了我的标题密钥。 enter image description here

所以我想知道为什么这不起作用,感觉就像一些明显的东西,但我无法得到这个工作。

感谢您的阅读。

+1

在我看来,req.body只是一个字符串,而引用req.body.title让你然后undefined导致跳进if块 – Kristianmitk

+1

确保你已经安装并启用了'body-parser'中间件(或者具有类似功能的一个)。编辑:并设置邮递员使用'应用程序/ json'为内容类型标题:) – damd

回答

3

我不知道邮差太清楚,但我要去猜测,主体内容类型设置为raw上传身体text/plain,这意味着body-parser将不以任何方式对其进行解析(console.log('body', typeof req.body)会显示“身体字符串“)。

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

+0

你是对的!这是一个愚蠢的错误! 我将其更改为'x-www-form-urlencoded',现在我看到了我的错误消息!谢谢! –