【问题标题】:Changing the Content-Type in axios header to fix a 415 error更改 axios 标头中的 Content-Type 以修复 415 错误
【发布时间】:2017-05-19 01:21:55
【问题描述】:

我正在尝试通过 axios 发布请求将文件发送到我的后端。

这是我目前遇到的错误:

cherrypy._cperror.HTTPError: (415, '预期内容实体 输入 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;边界=----WebKitFormBoundaryBwjjjGuJEySeXdRU

我不知道从这里去哪里。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript rest http reactjs axios


    【解决方案1】:
    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',
            }
        }
        )
    }
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,这会降低代码和解释的可读性!
    【解决方案2】:

    这对我有用:

    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】:

      您可以通过

      修复不同类型的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");
      });
      

      read more >>

      【讨论】:

        【解决方案4】:

        为了让 axios 包含 Content-Type: application-json 你需要这样做:

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

        【讨论】:

        • 你的代码 sn-p 中的有线 window.axios 是什么?
        猜你喜欢
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 2015-05-08
        • 2021-05-20
        • 1970-01-01
        • 2012-07-11
        • 2014-03-01
        相关资源
        最近更新 更多