我正在尝试通过axios post请求将文件发送到我的后端。
这是我目前的错误:
cherrypy._cperror.HTTPError:(415,'预期内容实体 键入application / json,text / javascript')
根据我的阅读,我需要在我的帖子请求中更改内容类型,我环顾四周,我正在尝试这样做:
handleUploadButton(e){
const upload_file = this.state.file;
const formData = new FormData();
formData.append('file', upload_file);
const request = axios.post(someUrl, formData, {headers: {
"Content-Type": "application/json"}
})
.then(function (response) {
console.log('successfully uploaded', upload_file);
});
}
不确定是否相关,但所有这些都是通过reactjs形式发生的。 这是我当前的Content-Type:Content-Type:multipart / form-data;边界= ---- WebKitFormBoundaryBwjjjGuJEySeXdRU
我不知道从哪里开始。任何帮助将不胜感激。
答案 0 :(得分:2)
SignIn = () => {
console.log('login clicked')
let data = JSON.stringify({
password: this.state.password,
username: this.state.email
})
axios.post('url', data, {
headers: {
'Content-Type': 'application/json',
}
}
)
}
答案 1 :(得分:1)
您可以通过以下方式修复不同类型的 catch()错误:
.catch((error)=> {
if(error.response){
this.errors(error.response.message);
}else if (error.request) {
console.log('error.request');
} else {
console.log('Error', error);
}
console.log("rejected");
});
答案 2 :(得分:0)
这对我有用:
const formData = new FormData();
formData.append('data', new Blob([JSON.stringify(data)], { type: 'application/json'}));
formData.append('file', file);
return axios.put(`${url}`, formData)
.then((response) => { console.log(response) })
.catch((error) => { console.log(error) })
我从另一个类似问题的答案中得到了这个。您可以查看原始答案here。
答案 3 :(得分:-2)
为了使axios包含 Content-Type:application-json ,您需要这样做:
javascript
window.axios = require('axios')
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'