如何使用 node js 和 react js 在 mongoDb 中上传图像

问题描述 投票:0回答:0

我曾尝试使用 multer npm 但它对我没有帮助:-

前端代码:-

const myFunction = (event) => {
    event.preventDefault();

    const formData = new FormData();
    formData.append('image', filePath);
    formData.append('title', Title);
    formData.append('description', Description);
    formData.append('day', dayset);
    formData.append('Time', Time);
    formData.append('Studio', Studio);
    formData.append('Episode', Episode);

 
    let config = {
      header : {
       'Content-Type' : 'multipart/form-data'
     }
    }

    axios({
      method: 'post',
      url: 'http://localhost:8888/Scheduler',
      data,
      config
    }).then(response => {
      console.log("getItems response:-", response);
      console.log('successfully uploaded', formData);
      // setData(response.data.Items);
    }).catch(error => {
      console.log("Error In Post Data getItems", error);
    });
  }

形式:-

 <form className="w-full max-w-lg">
<input className="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 
            leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="grid-city" type="text" placeholder="Albuquerque"
              value={Description} onChange={(e) => { setDescription(e.target.value) }} />
.
.
.
<input className="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 dark:text-gray-400 focus:outline-none 
            dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="file_input" type="file"
              onChange={(e) => setfilePath(e.target.files[0])} />
 <button className="flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 
        hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded" type="submit" onClick={(e) => myFunction(e)}>
          Sign Up
        </button>
      </form>

后端:-

ROUTER.JS

const express = require("express");
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const router = express.Router();
router.route("/").post(postSchedule,upload.single('File'));


controller.js
const postSchedule = async (req, res) => {
    console.log(req.body);
}

我试图在 controller.js 内的 postSchedule 函数中控制 req.body,但它只显示 {},没有别的。前端控制台接收到表单数据:{}

我怎样才能在后端收到req.body

node.js reactjs multer
© www.soinside.com 2019 - 2024. All rights reserved.