السلام عليكم
انا مستخدم هاذا الكود في ال post-controller
let express = require('express'),
multer = require('multer'),
mongoose = require('mongoose'),
uuidv4=require('uuid')
const DIR = './images/';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(' ').join('-');
cb(null, uuidv4() + '-' + fileName)
}
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
}
}
});
// انشاء الصورة
exports.create = (upload.single('image'),(req, res, next) => {
const url = req.protocol + '://' + req.get('host')
let model = new Post({
title: req.body.title,
content: req.body.content,
profileImg: `${req.protocol}://${req.get('host')}/images/${req.file.filename}`,
author: req.user.id
});
model.save()
.then(result => {
res.status(201).json({
message: "User registered successfully!",
userCreated: {
_id: result._id,
profileImg: result.profileImg
}
})
})
.catch(err => {
console.log(err),
res.status(500).json({
error: err
});
})
});
وايضا داخل ال craet-post-controller
import React from 'react';
import axios from 'axios';
import "bootstrap/dist/css/bootstrap.min.css";
//import { Button } from 'react-bootstrap';
const createError = require('http-errors');
class CreatePost extends React.Component {
constructor(props) {
super(props);
if (!localStorage.getItem('token')) {
this.props.history.push('/Login');//move to home page
}
this.onChangeTitle = this.onChangeTitle.bind(this);
this.onChangeContent = this.onChangeContent.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.renderError = this.renderError.bind(this);
this.state = {
title: '',
content: '',
profileImg: '',
error: ''
};
}
onChangeTitle(e) {
this.setState({
title: e.target.value,
error: ''
});
}
onChangeContent(e) {
this.setState({
content: e.target.value,
error: ''
});
}
onSubmit(e) {
e.preventDefault();
const formData = new FormData()
formData.append('profileImg', this.state.profileImg)
let data = {
title: this.state.title,
content: this.state.content,
};
axios.post('/api/posts', data)
.then(res => {
//alert(res.data.token);
this.props.history.push('/');//move to home page
})
.catch(err => {
if (err.title === ' ' && err.content === ' ') throw createError(404);
//alert(err.response.data.message)
this.setState({
error: err.response.data.message
});
})
}
renderError() {
return this.state.error ? (<blockquote>{this.state.error}</blockquote>) : "";
}
render() {
return (
<div className="container">
<div className="row">
<h4 className="mb-5"> انشاء صورة</h4>
{this.renderError()}
<form onSubmit={this.onSubmit} enctype="multipart/form-data">
<h3 className="mb-3"> العنوان </h3>
<div className="form-group mb-5">
<input className="form-input" type="text" value={this.state.title} onChange={this.onChangeTitle} placeholder="اضف عنوان للصورة " />
</div>
<h3 className="mb-3"> اضافة صورة </h3>
<div className="form-group mb-5">
<input type="file" className="form-input" name="image" defaultValue={this.state.profileImg} />
</div>
<h3 className="mb-3"> المحتوى </h3>
<div className="form-group mb-5">
<textarea className="form-input" value={this.state.content} onChange={this.onChangeContent} placeholder="اضف وصف للصورة "></textarea>
</div>
<div className="form-group">
<button className="btn button-primary button-outline" type="submit">ارسال</button>
</div>
</form>
</div>
</div>
);
}
}
export default CreatePost;
وايضا داخل ال post-model
const mongoose=require("mongoose");
const Schema=mongoose.Schema;
const CommentSchema=new Schema({
content:{
type:String,
required:true
},
author:{
type:Schema.Types.ObjectId,
ref:'User'
},
create_at:{
type:Date,
default:Date.now
},
});
const PostSchema=new Schema({
title:{
type:String,
required:true
},
profileImg: {
type: String
},
content:{
type:String,
required:true
},
author:{
type:Schema.Types.ObjectId,
ref:'User'
},
comments:[
CommentSchema,
],
create_at:{
type:Date,
default:Date.now
},
});
const Post=mongoose.model('Post',PostSchema);
module.exports=Post;
مش عارف ليه بيظهر نفس الخطا وحاولت ادور ع حل لكن من دون فاىدة؟