2017-01-04 99 views
0

我試圖通過axios post請求將文件發送到我的後端。更改axios標頭中的Content-Type以修復415錯誤

這是錯誤我目前有:

cherrypy._cperror.HTTPError: (415, 'Expected an entity of content type application/json, text/javascript')

從我讀書,我需要改變的Content-Type在我的崗位要求,我環顧四周,我目前正在試圖這樣做是這樣的:

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; border = ---- WebKitFormBoundaryBwjjjGuJEySeXdRU

我不知道該從哪裏出發。任何幫助將不勝感激。

回答

0

爲了使愛可信包括內容類型:應用JSON你需要做的是:

javascript window.axios = require('axios') axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

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

0
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', 
     } 
    } 
    ) 
} 
+0

雖然此代碼段可以解決的問題,[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高質量您的帖子。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! –

相關問題