首页 > 解决方案 > 通过 fetch 注册和理解 JSON 响应

问题描述

我对 React Native 比较陌生,我一直在学习课程并阅读文档。但是由于某种原因,我无法理解如何从 POST 请求中接收信息。在下面的代码中,我试图 POST 到我的测试服务器,但我不知道我是否通过,因为我不知道如何接收数据。

我花了很长时间才弄清楚如何实际发送信息(如果那是正确的,我的控制台日志只会告诉我这是我想要的)。

这是我的代码。如果我需要提供任何其他信息,请告诉我。

谢谢!

import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {View, Text, StyleSheet, TextInput, Button, Alert} from 'react-native';
import * as SecureStore from 'expo-secure-store';

export default class Registration extends Component {
    constructor(props) {
      super(props);
      
      this.state = {
        username: '',
        email: '',
        password: '',
      };
    }

    submitRegistration = () => {
        const { username, email, password } = this.state;
        console.log(this.state)

        fetch('https://toyshelf-api.herokuapp.com/api/auth/register', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: this.state.username,
            email: this.state.email,
            password: this.state.password
          }).then((response) => response.json())
          .then((json) => {return data.names}).catch((error) => {console.log(error)})
        });

    };

    render() {
        return (
            <View style={style.container}>
                <Text style={style.title} >Registration</Text>
                <TextInput 
                    style={style.input}
                    value={this.state.username}
                    placeholder="username"
                    onChangeText={(username) => this.setState({ username })}
                />
                <TextInput 
                    style={style.input} 
                    value={this.state.email}
                    placeholder="email"
                    onChangeText={(email) => this.setState({ email })}
                />
                <TextInput 
                    style={style.input} 
                    value={this.state.password}
                    placeholder="password"
                    autoCapitalize="none"
                    autoCorrect={false}
                    onChangeText={(password) => this.setState({ password })}
                />
                <Button title='Register' onPress={this.submitRegistration.bind(this)}/>
            </View>
        )
    };
};

const style = StyleSheet.create({
    container: {
        flex: 1,
        padding: 24,
        backgroundColor: "#eaeaea",
        marginTop: 24
    },
    title: {
        marginTop: 16,
        paddingVertical: 8,
        borderWidth: 4,
        borderColor: "#20232a",
        borderRadius: 6,
        backgroundColor: "#9bc2cf",
        color: "#20232e",
        textAlign: "center",
        fontSize: 30,
        fontWeight: "bold"
      },
      input: {
        marginTop: 16,
        paddingVertical: 8,
        borderWidth: 4,
        borderColor: "#20232a",
        borderRadius: 6,
        backgroundColor: "#61dafb",
        color: "#20232a",
        textAlign: "center",
        fontSize: 30,
        fontWeight: "bold"
      }
});```

标签: androidiosreactjsreact-nativemobile

解决方案


您的fetch函数调用需要修复。

fetch('https://toyshelf-api.herokuapp.com/api/auth/register', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    username: this.state.username,
    email: this.state.email,
    password: this.state.password
  })
}).then(response => console.log(Json.parse(response))).catch(error => console.log(error));

// fetch function call signature should be like this as it is asynchronous
fetch(url, options).then(response => {});

注意这里假设response服务器返回的是一个Json可以为parsed的字符串,否则你会得到运行时错误。请参阅MDN json 解析文档


推荐阅读