首页 > 解决方案 > 使用 Axios 将本机反应到 Django [错误:请求失败,状态码 400]

问题描述

我已经尝试了几乎所有选项,但没有通过。我的 Django 服务器与 Postman 一起工作正常,但是当我从我的 React Native 应用程序中尝试它时,它给出了一个错误

[Error: Request failed with status code 400]

我的代码是:

submitData = () => {
        console.log("submitQuestionDataToServer");
        let form_data = new FormData();
        form_data.append('qOne_img', Platform.OS === 'android' ? photoUri : photoUri.replace('file://', ''));
        form_data.append('qOne_img', Platform.OS === 'android' ? secondPhotoUri : secondPhotoUri.replace('file://', ''));
        form_data.append('question_title', qTitle);
        form_data.append('asked_by', "http://127.0.0.1:8000/auth/users/2/");
        let url = 'http://127.0.0.1:8000/api/questions/';
        axios.post(url, form_data, {
          headers: {
            "Content-Type": "multipart/form-data",
            "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1Nk",
        }
        })
            .then(res => {
                console.log("res *******")
              console.log(res.data);
            })
            .catch(err => console.log(err))
    }

提前致谢。

标签: iosdjangoreact-nativedjango-rest-frameworkaxios

解决方案


因为您正在向图像字段发送一个字符串。该应该是blob类型。

它应该是这样的:

const filePath = Platform.OS === 'android' ? photoUri : photoUri.replace('file://', '')
form_data.append('qOne_img',{uri: filePath, type: mimeType, name: fileName} );

不确定 uri 是否在本机反应中工作。我rn-fetch-blob用来处理 blob 的东西。

https://github.com/joltup/rn-fetch-blob#multipartform-data-example-post-form-data-with-file-and-data


推荐阅读