【问题标题】:How can I send form data with Axios and react native?如何使用 Axios 发送表单数据并做出原生反应?
【发布时间】:2021-08-18 21:50:15
【问题描述】:

为了不浪费你的时间,我尽量缩短代码和解释,

首先,一切正常……在哪里 在前端,照片选择器工作并已成功尝试。 在后端,Post API 正在运行并由 Postman 通过从数据上传文件进行测试,它给了我 200 个状态代码

但是当我发布图像时问题就出现了,但是使用React Native Android emulator时出现了这个错误

登录后台终端是 “错误:多部分:未找到边界”

这是代码,

import axios from 'axios';
import React, {useState} from 'react';
import {Button, View, Image} from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';

function ImageScreen() {
 
  const [image, setImage] = useState('');

  //   I think the error is here 
const postData = () => {
    axios
      .post(
        'http://10.0.2.2:3000/posts',
        {
          name: 'new post', // هنا اختصرت الكود حفظا للوقت
          image: image,
        },
        {
          headers: {
            'Content-Type': `multipart/form-data`,
          },
        },
      )
      .then(res => console.log(res.data))
      .catch(err => console.log(err));
  };

  //   That works fine I tested it, 
  const choosePhotoFromLibrary = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      compressImageQuality: 0.7,
    }).then(image => {
      console.log(image);
      setImage(image.path);
      this.bs.current.snapTo(1);
    });
    console.log(image);
  };

  return (
    <View>
      <Image style={{height: 300, width: 300}} source={{uri: image}} />
      <Button title="from device" onPress={choosePhotoFromLibrary} />
      <Button title="Post Data" onPress={postData} />
    </View>
  );
}

export default ImageScreen;

【问题讨论】:

  • axios 返回一个你应该使用 then catchasyncawait 的承诺
  • 我成功了,但是出现了新的错误,
  • 后台终端登录为“Error: Multipart: Boundary not found”
  • 你能和我们分享一下实际的例子吗?据我在这个例子中看到的问题是你没有提供一个有效的标题,在表单数据中你应该发送边界标题。

标签: reactjs react-native http axios multipartform-data


【解决方案1】:

你必须有“multipart/form-data”

试试看,


  const getData = () => {
    axios
      .get('http://10.0.2.2:3000/posts')
      .then(res => setData(res.data))
      .catch(err => console.log(err));
  };
  useEffect(() => {
    getData();
  }, []);

  function dataLogger() {
    console.log(image);
  }

  const postData = () => {
    let formData = new FormData();

    // const newImageUri = 'file:/' + image.split('file:/').join('');
    const newImageUri = 'file:///' + image.split('file:/').join('');

    formData.append('image', {
      uri: newImageUri,
      type: mime.getType(newImageUri),
      name: newImageUri.split('/').pop(),
    });
    formData.append('name', name);

    axios
      .post(`${baseURL}posts`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(res => console.log(res.data))
      .catch(err => console.log(err));
  };

【讨论】:

    【解决方案2】:

    要使用 axios 发送文件,您需要使用 FormData API。您构建一个表单并将文件(和相关数据)附加到它。这类似于将 enctype 设置为 "multipart/form-data" 的 HTML 表单元素。

    const form = new FormData();
    form.append('name', 'new post');
    form.append('image', image);
    
    axios.post('http://10.0.2.2:3000/posts', form);
    

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      相关资源
      最近更新 更多