我正在制作一个 MERN 应用程序,并在使用 Formidable 和 Cloudinary 在我的路线中发出 Post 请求时。 “路径”未定义。之前创建路线时,它在 Postman 中工作。但是在尝试在客户端进行 axios 调用后,我会收到一个 typeError 说“路径未定义”。这与使用 Cloudinary 通过表单上传的图像有关,但我不明白为什么路径未定义?
后端路由
// const express = require('express')
// const router = express.Router()
const router = require('express').Router();
const {House} = require('../../Models/House');
const Formidable = require('formidable');
const cloudinary = require('cloudinary').v2
const mongoose = require('mongoose');
require("dotenv").config()
// const { request, response } = require('express');
// const dotenv = require("dotenv");
// dotenv.config();
//mongoDB and Cloudinary
const mongoURI = process.env.Mongo_URI;
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key:process.env.API_KEY,
api_secret: process.env.API_SECRET
})
mongoose.connect(mongoURI, {useNewUrlParser:true, useUnifiedTopology:true}, (error)=>{
if(error) {
return console.log(error)
}
return console.log("database is connected")
})
router.post("/api/house-listing", (request, response)=>{
const form = new Formidable.IncomingForm();
form.parse(request, (error, fields, files)=>{
const {
price,
city,
county,
numOfBeds,
numOfBaths,
numOfGarages,
isSaleOrRent,
} = fields
const { houseImage } = files;
cloudinary.uploader.upload(houseImage.path, {folder:'/houseAgency/houses'}, async(error, result)=>{
if(error) {
console.log(error)
}
const image_url = result.url;
const newHouse = new House({
house_location: {
county: county,
city: city,
},
house_details: {
price: price,
numOfBeds: numOfBeds,
numOfBaths: numOfBaths,
numOfGarages: numOfGarages,
isSaleOrRent: isSaleOrRent,
house_image: image_url,
}
})
const savedHouse = await newHouse.save();
return response.status(200).json(savedHouse)
})
})
})
module.exports = router;
型号
const mongoose = require('mongoose');
const HouseSchema = mongoose.Schema({
house_location: {
city:{type:String, required: true},
county:{type:String, required: true}
},
house_details: {
price: { type: Number, required: true},
isSaleOrRent: {type: String, required: true},
numOfBeds: {type: Number, required: true},
numOfBaths: {type: Number, required: true},
numOfGarages: { type: Number, required: true},
house_image: {type: String, required: true}
}
});
const House = mongoose.model("House", HouseSchema);
module.exports = {House}