블로그 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 요청을 보내려고했습니다.
그러나 오류는 내가 title
누락 되었다고 말합니다 . 하지만 내 제목 키를 전달하고 있습니다.
그래서 이것이 왜 작동하지 않는지 궁금합니다. 명백한 것 같은 느낌이 들지만, 작동하도록 할 수 없습니다.
읽어 주셔서 감사합니다.
나는 너무 잘 이죠 몰라,하지만 난에 몸 콘텐츠 형식을 설정하는 추측거야 raw
으로 업로드 신체하는 text/plain
수단이되는 body-parser
(어떤 방법으로 그것을 구문 분석하지 않습니다 console.log('body', typeof req.body)
표시됩니다 "몸 문자열" ).
대신 콘텐츠 유형을로 설정하고 application/json
서버가의 JSON 미들웨어를 사용하는지 확인하십시오 body-parser
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다