Невозможно опубликовать данные файла изображения в JSON API в React-Native - PullRequest
0 голосов
/ 26 марта 2020

Я новичок в реагировании на родной язык и пытаюсь опубликовать данные фотографии, имени, фамилии и пола в базе данных API JSOn для добавления нового сотрудника, но при нажатии я получаю предупреждение "не аутентифицировано" на кнопку отправки. Если есть более простые способы, пожалуйста, сообщите мне. Вот мой код. Пожалуйста, проверьте мой код.

 import React, { Component } from 'react';
 import {
 StyleSheet,
 View,  Image,
 Text,TouchableOpacity,
 SafeAreaView, TextInput, 
  } from 'react-native';
  import ImagePicker from 'react-native-image-picker';

   export default class Profile extends Component {
   constructor(props) {
   super(props);
   this.state = {
   Fnametext: '',
   Lnametext: '',Gendertext:'',
   data: null,
   ImageSource: null,
   };
   }  
    onClickListener = async () => {
     const formData = new FormData();
     formData.append('photograph',this.state.ImageSource);
     formData.append('firstName', this.state.Fnametext);        
     formData.append('lastName', this.state.Lnametext);
     formData.append('gender', this.state.Gendertext);


   try {
   let response = await fetch(
    'http://104.197.28.169:3000/addEmp?',
    {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type':
          'application/json',
      },
      body: formData,
    },
  )
  if (
    response.status >= 200 && response.status < 300 ) 
    { 
    this.props.navigation.navigate(
      'Fourth',
     );
    }
  }
       catch (errors) {
          alert('not authenticated');
      }
    }
  selectPhotoTapped() {
   const options = {
  quality: 1.0,
  maxWidth: 500,
  maxHeight: 500,
  storageOptions: {
    skipBackup: true
  }
 };
ImagePicker.showImagePicker(options, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled photo picker');
  }
  else if (response.error) {
    console.log('ImagePicker Error: ', response.error);
  }
  else if (response.customButton) {
    console.log('User tapped custom button: ', response.customButton);
  }
  else {
    let source = { uri: response.uri }
   this.setState({

      ImageSource: source,    
    });
   }
  });
 }

   render() {
     {
      return (
    <View style={styles.container}>
      <SafeAreaView>
       <TouchableOpacity style={{ alignItems: 'center', justifyContent: 'center' }}
          onPress={this.selectPhotoTapped.bind(this)}>
          <View style={styles.ImageContainer}>
            {this.state.ImageSource === null ? <Image style={{ width: 170, height: 170 }}
              source={require('../images/default-profile.jpg')}></Image> :
              <Image
                style={{ width: 150, height: 150, borderRadius: 80 }}
                source={this.state.ImageSource} />
            }
          </View>
        </TouchableOpacity>
        <View style={styles.name}>
          <Text style={styles.label}>First Name:</Text>
          <TextInput style={styles.Shable}
            onChangeText={Fnametext => this.setState({ Fnametext })
            }></TextInput>
        </View>
        <View style={styles.name}>
          <Text style={styles.label}>Last Name:</Text>
          <TextInput style={styles.Shable}
            onChangeText={Lnametext => this.setState({ Lnametext })
            }></TextInput>
        </View>
         <View style={styles.name}>
            <Text style={styles.label}>Gender:</Text>
            <TextInput  style={styles.Shable}
              onChangeText={Gendertext => this.setState({ Gendertext })
              }></TextInput>
          </View>
        <View style={styles.name}>
          <TouchableOpacity style={{  width: '100%',paddingTop: 15,paddingBottom: 
       10,backgroundColor: '#2F6995',
           borderRadius: 20,borderWidth: 1,borderColor: '#fff', }}
            onPress={this.onClickListener}
            underlayColor="#fff">
            <Text style={{ color: '#fff', textAlign: 'center', paddingLeft: 10,
                paddingRight: 10, fontSize: 15, }}>
               SUBMIT
              </Text>
          </TouchableOpacity>
        </View>
       </SafeAreaView>
    </View>
        );
     }
    }
  }
 const styles = StyleSheet.create({
 container: {
 flex: 1,
 marginRight: 10,
 marginLeft: 10,
  backgroundColor: '#F5FCFF',
 },
   name: {
 //backgroundColor: "gray",
 flexDirection: 'row',
 height: 50,
 width: '100%',
 marginTop: 15,
 },
  label: {
 flex: 1,
 marginTop: 15,
 height: 40,
 fontSize: 15,
 width: 50,
 marginLeft: 20,
  },
  Shable: {
 fontSize: 15,
 borderWidth: 0.5,
 width: '60%',
 borderColor: 'black',
 height: 40,
 marginTop: 10,
 },
});
...