как решить эту проблему, не могу опубликовать ошибку в MERN?

#node.js #reactjs #mern

Вопрос:

Я вставляю два изображения вместе с данными формы в базу данных MongoDB. Хотя оба изображения хранятся в папке «Мой компьютер», но все данные формы не загружаются в базу данных.

ошибка

 lt;!DOCTYPE htmlgt; lt;html lang="en"gt; lt;headgt; lt;meta charset="utf-8"gt; lt;titlegt;Errorlt;/titlegt; lt;/headgt; lt;bodygt; lt;pregt;Cannot POST /lt;/pregt; lt;/bodygt; lt;/htmlgt;  

в моей консоли. Пожалуйста, помогите мне, как это решить.

Я попробовал некоторые ранее заданные вопросы в stackOF.

app.js

 const express = require("express") const app = express() const cors = require('cors'); const env = require("dotenv")  const port = 5000 env.config({path: "../server/config.env"}) require("../server/db/conn") app.use(cors()); app.use(express.json()) app.use(require("../server/router/auth"))   app.listen(port, (err) =gt; {  if (err) {  return console.error(err);  }  return console.log(`server is listening on ${port}`); });  module.exports = "conn"  

register.js(интерфейс)

  const Register = () =gt; {  const [newUser, setNewUser] = useState({  school: "",  address: "",  photo: "",  photoone: ""  });   const handleSubmit = (e) =gt; {  e.preventDefault();  const formData = new FormData();  formData.append("school", newUser.school);  formData.append("photo", newUser.photo);  formData.append("photoone", newUser.photoone)  formData.append("address", newUser.address);    axios({  method: "post",  url: "/teacher",  data: formData,  headers: { "Content-Type": "multipart/form-data" },  })  .then((response) =gt; {  console.log(response)  }).then((data) =gt; {  console.log(data)  }).catch((error) =gt; {  if (error.response) {  console.log(error.response.data)  }  })  };   const handleChange = (e) =gt; {  setNewUser({ ...newUser, [e.target.name]: e.target.value });  };   const handlePhoto = (e) =gt; {  setNewUser({ ...newUser, photo: e.target.files[0] });  };   const handlePhotoone = (e) =gt; {  setNewUser({ ...newUser, photoone: e.target.files[0] });  };   return (  lt;gt;  lt;div className="container main"gt;  lt;div className="row"gt;  lt;div className="col-sm-6 col-md-6 col-lg-6"gt;  lt;form onSubmit={handleSubmit} encType="multipart/form-data"gt;  lt;div class="mb-3"gt;  lt;label class="form-label"gt;  Your school  lt;/labelgt;  lt;input  type="text"  class="form-control"  id="exampleInputPassword1"  id="school"  name="school"  value={newUser.school}  onChange={handleChange}  /gt;  lt;/divgt;   lt;div class="input-group mb-3"gt;  lt;input  type="file"  id="pic"  accept=".png, .jpg, .jpeg"  name="photo"  onChange={handlePhoto} type="file" class="form-control" id="inputGroupFile02" /gt;  lt;/divgt;   lt;div class="input-group mb-3"gt;  lt;input  type="file"  id="pic"  placeholder="second photo"  accept=".png, .jpg, .jpeg"  name="photoone"  onChange={handlePhotoone} type="file" class="form-control" id="inputGroupFile01" /gt;  lt;/divgt;       lt;div class="mb-3"gt;  lt;label for="exampleInputEmail1" class="form-label"gt;  your address  lt;/labelgt;  lt;input  type="text"  id="address"  name="address"  value={newUser.address}  onChange={handleChange}  class="form-control"  aria-describedby="emailHelp"  /gt;    lt;/divgt;  lt;button  value="register"   type="submit"  class="btn btn-primary"  gt;  Submit  lt;/buttongt;  lt;/formgt;  lt;/divgt;  lt;/divgt;  lt;/divgt;  lt;/gt;  ); };  

auth.js(backend)

 const mongoose = require("mongoose") const express = require("express") const router = express() require("../db/conn") const User = require("../model/userSchema") const Teacher = require("../model/userSchemaTeacher") const multer = require('multer'); let path = require('path'); let fs = require("fs-extra");    const storage = multer.diskStorage({  destination: function (req, file, cb) {  let schoolname = req.body.school;  let path = `C:/Users/kumar/Desktop/mern/server/images/${schoolname}`;   fs.mkdirsSync(path);  cb(null, path);  // cb(null, 'images');  },  filename: function (req, file, cb) {  cb(null, file.originalname);   } });   const fileFilter = (req, file, cb) =gt; {  const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];  if (allowedFileTypes.includes(file.mimetype)) {  cb(null, true);  } else {  cb(null, false);  } }  let upload = multer({ storage, fileFilter });   router.route('/teacher').post(upload.fields([{  name: "photo", maxCount: 1 }, {  name: "photoone", maxCount: 1 } ])), (req, res) =gt; {   const school = req.body.school;  const photo = req.file.filename  const photoone = req.file.filename  const address = req.body.address;    const newUserData = {  school,  photo,  photoone,  address,   }   const newUser = new Teacher(newUserData);   newUser.save()  .then(() =gt; res.json('User Added'))  .catch((err) =gt; {  console.log(err);  }); }   

Пожалуйста, посмотрите, как это решить?

Ответ №1:

Маршрут, по которому вы пытаетесь POST получить данные вашей формы, не определен, пожалуйста, задайте свой маршрут следующим образом:

 router.post('/teacher',upload.fields([{  name: "photo", maxCount: 1 }, {  name: "photoone", maxCount: 1 } ]), (req, res) =gt; {   const school = req.body.school;  const photo = req.files['photo'][0]  const photoone = req.files['photoone'][0]  const address = req.body.address;    const newUserData = {  school,  photo,  photoone,  address,   }   const newUser = new Teacher(newUserData);   newUser.save()  .then(() =gt; res.json('User Added'))  .catch((err) =gt; {  console.log(err);  }); }) ...  

Комментарии:

1. Error: Route.post() requires a callback function but got a [object String] показывает эту ошибку

2. получив эту ошибку Error: Route.post() requires a callback function but got a [object String] , изменение олни здесь router.route('/teacher').post('/',upload.fields.... ??

3. обновленный ответ. пожалуйста, измените, как это

4. все то же самое Error: Route.post() requires a callback function but got a [object String]

5. это приходит Error: TEACHER validation failed: photo: Cast to string failed for value "{ fieldname: 'photo', originalname: 'aadhar_rahul_back.png', encoding: '7bit', mimetype: 'image/png', destination: 'C:/Users/kumar/Desktop/mern/server/images/dd', filename: 'aadhar_rahul_back.png', path: 'C:\Users\kumar\Desktop\mern\server\images\dd\aadhar_rahul_back.png', size: 232132 }" (type Object) at path "photo", photoone: Cast to string failed for value "{ fieldname: 'photoone', originalname: 'rahul.jpg', encoding: '7bit', mimetype: 'image/jpeg',