You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native POST请求返回数据接收问题求助

Fixing Your React Native POST Request & Response Handling

Hey there! I noticed a couple of key issues in your code that are preventing you from capturing the POST response, plus I'll walk you through how to properly handle the returned data so you can confirm if your registration request succeeds.

First: The Critical Syntax Error

Looking at your fetch call, you accidentally nested the .then() chain inside the body property of the fetch options. That's why you're not seeing any response data—your promise chain isn't actually attached to the fetch request at all!

Fixed Code with Proper Response Handling

Here's the corrected version of your submitRegistration method, plus some improvements to help you debug and use the returned data:

submitRegistration = () => {
  const { username, email, password } = this.state;
  console.log("Submitting data:", 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, email, password }) // Shorthand since variable names match API keys
  })
  .then((response) => {
    // First, check if the HTTP request was successful (status code 200-299)
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json(); // Parse the JSON response from the server
  })
  .then((jsonResponse) => {
    // This is where you access the returned data!
    console.log("Registration Success! Server Response:", jsonResponse);
    
    // Do something useful with the data—like store a token, navigate, or show feedback
    Alert.alert("Success!", `Welcome aboard, ${jsonResponse.username || username}!`);
    
    // Optional: Reset the registration form
    this.setState({ username: '', email: '', password: '' });
  })
  .catch((error) => {
    // Handle all errors (network issues, invalid input, server errors, etc.)
    console.error("Registration Failed:", error.message);
    Alert.alert("Oops!", `Registration didn't work: ${error.message}`);
  });
};

Key Improvements Explained:

  • Fixed Promise Chain: Moved the .then() calls outside the fetch options object so they properly attach to the fetch promise.
  • HTTP Status Check: Added !response.ok to catch non-200 status codes (like 400 for invalid email or 500 for server crashes)—this ensures you don't treat error responses as successful.
  • Explicit Response Handling: The jsonResponse variable holds all the data sent back from your API. You can access properties like jsonResponse.token or jsonResponse.message depending on what your server returns.
  • User Feedback: Added Alert calls to let the user know if the registration worked or failed, which is more helpful than just logging to the console.
  • Cleaner Code: Used object shorthand ({ username, email, password }) since your state variables match the API's expected keys.

Bonus: Using Async/Await (Optional)

If you prefer a more readable syntax, here's the same function rewritten with async/await:

submitRegistration = async () => {
  const { username, email, password } = this.state;
  console.log("Submitting data:", this.state);

  try {
    const response = await fetch('https://toyshelf-api.herokuapp.com/api/auth/register', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, email, password })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const jsonResponse = await response.json();
    console.log("Registration Success! Server Response:", jsonResponse);
    Alert.alert("Success!", `Welcome aboard, ${jsonResponse.username || username}!`);
    this.setState({ username: '', email: '', password: '' });
  } catch (error) {
    console.error("Registration Failed:", error.message);
    Alert.alert("Oops!", `Registration didn't work: ${error.message}`);
  }
};

Quick Extra Tip:

You don't need this.submitRegistration.bind(this) in your Button's onPress—since you defined submitRegistration as an arrow function, it already binds this to the component automatically. You can simplify it to onPress={this.submitRegistration}.

内容的提问来源于stack exchange,提问作者CaptainKirk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:39:56