gpt4 book ai didi

node.js - 将 Multer 验证错误传递给 React 组件

转载 作者:搜寻专家 更新时间:2023-10-31 23:29:18 25 4
gpt4 key购买 nike

我正在学习 Multer 以及 ReduxReact

我的express 路由器是这样的

router.post('/upload', addressController.uploadImage);

我的Multer代码如下

const uploadImage = (req, res, next) => {

const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});

const fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(new Error('Try to upload .jpeg or .png file.'), false);
}
};

const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
}).single('addressImage');

upload(req, res, function(error) {
if (error) {
// An error occurred when uploading
res.status(500).json({
message: error // I would like to send error from Here.
});
console.log(error);
} else {
if (req.file.filename === res.req.res.req.file.filename) {
res.status(200).json({
message: 'File uploaded',
file: req.file.filename
});
}
return;
}
});
}

我的操作如下

export const uploadImage = (formData, id, config) => dispatch => {
return Axios.post('/api/address/upload', formData, config)
.then(response => {
dispatch({
type: 'uploadImage',
payload: response.data
});
})
.catch(error => {
dispatch({
type: 'uploadImage',
payload: error // I would like to pass error through here.
});
return false;
});
};

我的 Reducer 如下所示

const addressReducer = (state = initialState, action) => {
switch (action.type) {
case 'getAddresses': {
return {
...state,
controlModal: action.payload.valueModal,
address: action.payload.addressData
};
}
case 'uploadImage': {
return {
...state,
uploadImage: action.payload
};
}
default:
return state;
}
};

我想在我的组件中得到如下错误

render() {
console.log(this.props.uploadImage);
}


const mapStateToProps = state => ( {
uploadImage: state.addressReducer.uploadImage
} );


export default connect(mapStateToProps)(ModalElement);

我的控制台输出如下

enter image description here

当我尝试上传不带 .jpeg 和 .png 扩展名的文件时,我的 React 组件如何出现 Try to upload .jpeg or .png file. 错误?

最佳答案

您不必发送 500 状态码,而是应该发送 400

 res.status(400).json({
message: error // I would like to send error from Here.
});

关于node.js - 将 Multer 验证错误传递给 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55508211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com