我有一个Node.js博客API。目前,我使用Insomnia发布了一个包含标题和内容的Json对象。我现在想在帖子中添加图片。
我的Json看起来像这样:
{
"post": {
"title": "My title",
"content": "This content",
"image": "/path/to/image.jpg"
}
}
我的addPost函数包含:
newPost.image.data = fs.readFileSync(newPost.image);
newPost.image.contentType = 'image/jpeg';
// Let's sanitize inputs
newPost.title = sanitizeHtml(newPost.title);
newPost.content = sanitizeHtml(newPost.content);
我收到此错误:
TypeError: Cannot create property 'data' on string '/path/to/image.jpg'
我认为这是因为newPost.image.data
需要一个对象,但是fs.readFileSync(newPost.image)
是一个字符串。我不知道该如何处理。有人可以提供任何建议吗?
完整的addPost功能:
完整的邮政编码:
PostController.addPost = async (req, res) => {
try {
if (!req.body.post.title || !req.body.post.content) {
res.status(403).end();
}
const newPost = new Post(req.body.post);
newPost.image = {};
newPost.image.data = fs.readFileSync(newPost.image);
newPost.image.type = 'image/jpeg';
// Let's sanitize inputs
newPost.title = sanitizeHtml(newPost.title);
newPost.content = sanitizeHtml(newPost.content);
newPost.slug = slug(newPost.title.toLowerCase(), { lowercase: true });
newPost.cuid = cuid();
newPost.save((err, saved) => {
if (err) {
res.status(500).send(err);
}
res.json({ post: saved });
});
}
catch (err) {
console.log(err);
}
}
发布
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const postSchema = new Schema({
title: { type: 'String', required: true },
content: { type: 'String', required: true },
image: { data: Buffer, type: 'String', required: true }, //added when trying to get the image to post
slug: { type: 'String', required: true },
cuid: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
});
let Post = mongoose.model('Post', postSchema);
export default Post;
答案 0 :(得分:1)
将newPost.image = {}
初始化为空对象,然后分配值
newPost.image.data = fs.readFileSync(newPost.image);
newPost.image.contentType = 'image/jpeg';