我无法成功返回要查看的响应消息。我以前可以这样做,但在对中间件和route.post进行一些更改以查看是否捕获已上传的文件后,我不再能够捕获错误。我在后端使用node js,在前端使用react js。
ReactJS
import React, { useState, useEffect } from 'react';
import './NewsAndFlyerUploadFlyers.css';
//Components
import Header from '../../Components/Header/Header';
import Footer from '../../Components/Footer/Footer';
//Repositories
import Axios from 'axios';
import { useNavigate } from 'react-router-dom';
import moment from 'react-moment';
const NewsAndFlyerUploadFlyers = () => {
const [flyerName, setFullName] = useState(null);
const [flyerEventDate, setFlyerEventDate] = useState(null);
const [flyerDescription, setFlyerDescription] = useState(null);
const [selectedFile, setSelectedFile] = useState(null);
const [statusMessage, setStatusMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const Navigate = useNavigate();
const submitForm = () => {
setIsLoading(true);
const url = 'http://localhost:3001/Flyer/Flyer_Upload';
const data = new FormData();
data.append('flyerName', flyerName);
data.append('flyerEventDate', flyerEventDate);
data.append('flyerDescription', flyerDescription);
for (var x = 0; x < selectedFile.length; x++){
data.append('files', selectedFile[x]);
}
Axios.post(url, data)
.then((response) => {
if (response.data.message != null){
setStatusMessage(response.data.message);
}
else {
Navigate('/NewsAndFlyers');
}
});
setIsLoading(false);
};
return (
<>
<Header/>
<div className='newsAndFlyersUploadFlyersBody'>
<h1>Upload A Flyers</h1>
<div className='flyerInfoFormBody'>
<p className='flyerName'>*Event Name: <input name='flyerName' placeholder='Event Name' required autoComplete="off" onChange={(e) => setFullName(e.target.value)} /></p>
<p className='flyerEventDate'>*Event Date: <input name='flyerEventDate' type='date' placeholder='Event Date' required autoComplete="off" onChange={(e) => setFlyerEventDate(e.target.value)} /></p>
<p className='flyerDescription'>*Flyer Description: <textarea name='flyerDescription' placeholder='Flyer Description' required autoComplete="off" onChange={(e) => setFlyerDescription(e.target.value)} /> </p>
<p>*Upload the flyer.</p>
<input className='uploadFiles' type='file' name='file' required onChange={(e) => setSelectedFile(e.target.files)} /></div>
{isLoading && <button className='uploadButton' disabled>Loading</button>}
{!isLoading && <button className='uploadButton' onClick={submitForm}>Upload Flyer</button>}
<h2>{statusMessage}</h2>
</div>
<Footer/>
</>
);
}
export default NewsAndFlyerUploadFlyers;
Node JS 中间件:
const flyerDestination = './routes/Flyers'
const flyerStorage = multer.diskStorage({
destination: function (req, file, cb){
return cb(null, flyerDestination)
},
filename: function (req, file, cb){
if (fs.existsSync(path.join(flyerDestination,file.originalname))) {
return cb(new Error("Flyer already exists"));
} else {
return cb(null, file.originalname);
}
}
});
const flyerUpload = multer({ storage: flyerStorage }).array('files');
Node JS 路线.post
router.post('/Flyer_Upload', (req, res) => {
flyerUpload(req, res, function (err) {
const flyerName = req.body.flyerName;
const flyerEventDate = req.body.flyerEventDate;
const flyerDescription = req.body.flyerDescription;
const flyerID = Math.floor(Math.random()*90000) + 10000;
const flyerDirectory = 'http://localhost:3001/Flyers/';
var uploadFlyer = true;
var multerMessage = null;
if (err instanceof multer.MulterError) {
uploadFlyer = false;
multerMessage = 'An Error Occurred During Upload!';
} else if (res.status(409)) {
uploadFlyer = false;
multerMessage = 'Flyer already exists';
} else if (res.status(500)){
uploadFlyer = false;
multerMessage = 'A Bad Request Was Recieved!';
} else if (err){
uploadFlyer = false;
multerMessage = 'An Unknown Error Occurred!';
}
if (multerMessage == null){
for (const file of req.files) {
directory = path.dirname(file.path);
const flyerUploadedPath = flyerDirectory + file.filename
//Delete Once Successful
console.log('flyerName: ' + flyerName);
console.log('flyerEventDate: ' + flyerEventDate);
console.log('flyerDescription: ' + flyerDescription);
console.log('flyerID: ' + flyerID);
console.log('File path: ' + flyerUploadedPath);
db.query('INSERT INTO flyerinfo (flyerID, flyerName, flyerEventDate, flyerDescription, flyerURL) VALUES (?,?,?,?,?)', [flyerID, flyerName, flyerEventDate, flyerDescription, flyerUploadedPath], (err, res) => {
if (err){
return res.json({message: 'An Error Occurred!' });
}
});
return res.status(200).send(req.files);
}
} else {
console.log (multerMessage)
return res.json({message: multerMessage });
}
});
});
module.exports = router;
你可以这样做:
Axios.get(url, data)
.then(() => {
//...
})
.catch((error) {
console.log(error.request); //Or error.message
});
捕获错误。 您还可以查看此axios docs
使用 try catch 子句来捕获错误