我试图以响应的方式向我的API发送一个Post请求,但收到错误的语法错误。我在StackOverflow上提到了这篇文章,但是我的代码看不出有什么区别。
React.js, how to send a multipart/form-data to server
export default class CapsuleForm extends React.Component {
constructor (props) {
super(props);
this.state = {
userUrl: this.props.auth.domain + "/users/" + this.props.userID,
dateToPost: moment(),
image: "",
caption: "",
redirect: false
};
this.handleChange = this.handleChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
var form = new FormData()
form.append("user", this.state.userUrl);
form.append("dateToPost", this.state.dateToPost.format());
form.append("image", this.state.image.files[0]);
form.append("caption", this.state.caption);
for (var pair of form.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
this.props.auth.postCapsule(
form
).then(() => {
this.setState({redirect: true})
})
.catch(err =>{
alert(err);
})
}
handleDateChange(date) {
this.setState({
dateToPost: date
});
}
handleChange(e) {
this.setState(
{
caption: e.target.value
}
)
}
render() {
function FieldGroup({ id, label, help, ...props }) {
return (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
</FormGroup>
);
}
return (
<Form onSubmit={this.handleFormSubmit.bind(this)}>
<h1> Create a SnapCapusle </h1>
{/* TODO Find out why FieldGroup component does not pass onChange function
correctly */}
<ControlLabel> Date </ControlLabel>
<DatePicker
selected={this.state.dateToPost}
onChange={this.handleDateChange}
style={ css }
showTimeSelect
dateFormat="LLL"
/>
<FormGroup id="1">
<ControlLabel> File </ControlLabel>
<FormControl
type="file"
label="Image"
name="image"
inputRef={ref => {
this.state.image = ref;
}}
/>
</FormGroup>
<FormGroup id="2">
<ControlLabel> Caption </ControlLabel>
<FormControl
type="text"
placeholder="Enter text"
name="caption"
onChange={this.handleChange}
/>
</FormGroup>
<FormGroup>
<Button type="submit"> Submit </Button>
</FormGroup>
</Form>
);
}
}
这是PostCapsule函数。
postCapsule(formData) {
console.log("PostCapsule called to " + `${this.domain}/snapcapsule/`)
return fetch(`${this.domain}/snapcapsule/`, {
method: 'POST',
credentials: 'same-origin',
body: formData
})
}