React Native:当我使用文件发出 http 请求时,Form Data() 的变量在 React Native 应用程序中被记录为未定义

ReactNative : variable for FormData() being logged as undefined in ReactNative application when i make an http request with a file

我一直在尝试在 android 模拟器上从我的 React 本机应用程序发出 post 请求,但我在请求正文中发送的对象被 vvalue 为未定义,一直在努力解决这个问题,但没有成功。请帮助我

这是我在名为 "API.js" 的应用程序中的表单代码,其名称仅用于测试 API 端点

import React, { Component } from "react";
import {
  Text,
  TextInput,
  View,
  TouchableHighlight,
  StyleSheet,
  Button,
  FormData
} from "react-native";
import Permissions from "react-native-permissions";
import ImagePicker from "react-native-image-crop-picker";
import axios from "axios";

var styles = StyleSheet.create({});
var msg = "Select Image";
var data;

export default class API extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      price: "",
      size: "",
      description: "",
      image: "",
      popularity: ""
    };
  }
  FormDataFunc() {
    let form = new FormData();
    form.append("name", this.state.name);
    form.append("price", this.state.price);
    form.append("size", this.state.size);
    form.append("description", this.state.description);
    form.append("image", this.state.image);
    form.append("popularity", this.state.popularity);
    return form; 
    return form;
  }
  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }
  Submit() {
    axios({
      method: "post",
      url: "http://192.168.0.102:3000/products",
      data: this.FormDataFunc,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: this.FormDataFunc
    })
      .then(() => {
        console.log("DONE!");
        this.props.navigation.navigate("offersScreen");
      })
      .catch(err => {
        console.log(err);
        console.log(this.FormDataFunc);
      });
  }
  componentDidMount() {
    Permissions.check("photo").then(response => {
      // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
      console.log(response);
    });
  }

  render() {
    const image = () => {
      ImagePicker.openPicker({
        multiple: false,
        includeBase64: true
      }).then(images => {
        console.log(images);
        this.setState({
          images: { data: `\`${images.mime}\`;base64,\`${images.data}\`` }
        });
        console.log(this.state.images);
        msg = "Selected";
      });
    };
    return (
      <View>
        <TextInput placeholder="Name" name="name" />
        <TextInput placeholder="Price" name="price" />
        <TextInput placeholder="Size" name="size" />
        <TextInput placeholder="Description" name="description" />
        <TouchableHighlight onPress={image} name="image">
          <Text>{msg}</Text>
        </TouchableHighlight>
        <TextInput placeholder="Popularity" name="popularity" />
        <TouchableHighlight title="Submit" onPress={this.Submit}>
          <Text>Send</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

这是我的后端路由 "product.js" 的代码,它接收请求(node.js 并表达)

const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const path = require("path");
const cloudinary = require("cloudinary");
const mongoose = require("mongoose");

//Product Model

const product = require("../models/product").product;
router.use(bodyParser.json());

//GET route

router.get("/", (req, res) => {
  product.find().then(product => res.json(product));
});

// POST route
cloudinary.config({
  cloud_name: "cloud222",
  api_key: "783935981748815",
  api_secret: "uY47vBS1rI2x5jvFtnXQIjMMqU0"
});

router.post("/", (req, res) => {
  //MISC//
  let imageUrl;
  console.log("starting");
  //MISC//

  //CLOUDINARY UPLOAD
  cloudinary.v2.uploader.upload(req.body.image, (error, result) => {
    if (error) {
      console.log(error);
      console.log(`${req.body.image}`);
    } else {
      imageUrl = result.secure_url;
      //MONGO UPLOAD
      var productv = {
        name: req.body.name,
        price: req.body.price,
        size: req.body.size,
        description: req.body.description,
        image: imageUrl,
        popularity: req.body.popularity
      };
      const productvar = new product(productv);
      productvar
        .save()
        .then(product => console.log(product))
        .then(product => res.json(product))
        .catch(err => console.log(err));
    }
  });

  //END//
});

module.exports = router;

数据被记录为未定义,因此请求没有得到响应

我认为问题在于您创建了一个 FormData 并想 post 它,但是您添加的 headers 是 "application/json"。你应该改变它:

 headers: {
         'content-type': 'multipart/form-data',
         'Accept':'multipart/form-data',
      },

希望对你有用。

问题已解决

必须使用 onChangeText = 而不是 onChange 因为 onChange 不是 return 字符串