[英]Upload File Api request works in postman but not in nodejs and react MERN
我正在上傳文件和媒體 API,在 Postman 中工作正常,但在代碼中不行
反應代碼:
campaignChangedHandler = (event) => {
this.setState(
{
campaignFile: document.getElementById('campaignFile').files[0]
})
};
onSubmit = async(e) => {
let formData = new FormData();
formData.append('campaignFile', this.state.campaignFile);
const headers = {
'Authorization': `Bearer ${token}`
};
await axios.post('http://localhost:3001/upload/', {formData}, {headers}).then(resp => {
console.log(resp)
})
};
render() {
return (
<form onSubmit={this.onSubmit}>
<input value={this.state.data} error={errors.data}
onChange={this.campaignChangedHandler}
name={"campaignFile"}
id="campaignFile"
type="file"/>
</form>
)
}
節點 JS 代碼:
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.post('/upload', function (req, res) {
console.log(req.files);
}
我總是在 Nodejs 控制台中得到 UNDEFINED,我嘗試使用多方、multer、busboy,但我得到了相同的結果,但是在 postman 我得到了這個:
嘗試這個:
constructor(props) {
super(props);
this.state = {
campaignFile: null
}
}
onChangeHandler=event=>{
this.setState({
campaignFile: event.target.files[0],
})
}
onSubmit = async(e) => {
let formData = new FormData();
formData.append('campaignFile', this.state.selectedFile);
const headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
};
await axios.post('http://localhost:3001/upload/',formData,headers).then(resp => {
console.log(resp)
})
};
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="file" name="campaignFile" onChange={this.onChangeHandler}/>
</form>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.