我想提交一个包含“图像”和“类别名称”的表单,但是在我的ExpressJS(后端)中无法获取数据。在express中,我使用了“express-fileupload”包。以下是我的代码,请帮助我解决这个问题。
前端(React-CategoryForm.js):
在
注意:如果我从React仅传递数据(而不是图像),例如
前端(React-CategoryForm.js):
import axios from "axios";
import React, { Component } from "react";
class CategoryForm extends Component {
constructor(props) {
super(props);
this.state = { name: '', file: '', fileName: '' };
this.onChange = this.onChange.bind(this);
this.onChangeImageHandler = this.onChangeImageHandler.bind(this);
this.onCreate = this.onCreate.bind(this);
}
/** Methods */
onChange = e => this.setState({ [e.target.name]: e.target.value });
onChangeImageHandler = e => this.setState({ fileName: e.target.files[0].name, file: e.target.files[0] });
onCreate = async e => {
e.preventDefault();
e.stopPropagation();
const formData = new FormData();
formData.append('name', this.state.name);
formData.append('file', this.state.file);
const url = 'http://localhost:4000/api/v2/categories';
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkZTc3MDM0NTgxM2QyN2NmZDExMWE3ZSIsImVtYWlsIjoiaGFyc2hhQHNrcmVlbS5pbyIsImlhdCI6MTU3NTQ0ODc1OSwiZXhwIjoxNTc2MzEyNzU5fQ.7wxCmPhkzb0aaB4q9PBKmHAj1Klw1NQmp1nBI3NsRRI';
axios({
method: 'POST',
url: url,
headers: {
Authorization: `Bearer ${token}`,
ContentType: 'multipart/form-data'
},
body: formData
})
.then(res => this.setState({ name: '', file: '', fileName: '' }))
.catch(err => console.log('Error - ', err));
}
/** Rendering the Template */
render() {
const { name, fileName } = this.state;
return (
<form onSubmit={this.onCreate}>
<input type="text" name="name" value={name} onChange={this.onChange} placeholder="New Category Name" />
<input type="file" name="file" onChange={this.onChangeImageHandler} />
<button type="submit">Add Category</button>
</form>
)
}
}
export default CategoryForm;
后端(ExpressJS:server.js)
const express = require("express");
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/api/v2/categories',
(req, res, next) => { console.log(req.body); },
require("./categoryRoute"));
在
req.body
中,我得到了{ }。请告诉我如何将图像与文本数据一起发送到Express。注意:如果我从React仅传递数据(而不是图像),例如
data: {name: 'Shivam'}
,则会在后端收到它。