React Native如何获取Flask API返回的登录接口数据?
How to Fetch and Use Returned Data from Your Flask Backend in React Native
Looks like you've already got the request sending and backend processing sorted out—great work! The missing piece is handling the response from fetch to extract the data your Flask server sends back. Here's how to adjust your React Native code to get and use that result data:
Updated Request Code with Response Handling
try { // First, send the request and get the raw response object const response = await fetch('http://192.168.5.12:5000/login', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ data: result.user.email }) }); // Parse the response body into a JavaScript object (this is async too!) const returnedData = await response.json(); // Now you can work with the data from your backend console.log('Backend response:', returnedData); // Based on your Flask code, the response is an array of user ID objects // Access the ID like this (adjust if your schema returns a different structure) if (returnedData.length > 0) { const userId = returnedData[0].id; console.log('Extracted user ID:', userId); // Example: Store the ID in state or use it for further requests // setUserId(userId); // If using useState hook } } catch (error) { // Handle any errors that occur during the request (network issues, server errors) console.error('Request failed:', error); }
Key Steps Explained
- The initial
await fetch(...)returns a Response object, not the actual JSON data. You need to explicitly parse it withresponse.json(). - Since
response.json()is also an asynchronous operation, you have to useawaitagain to get the parsed data. - Your Flask code uses
users_schema.dump(id), which will return an array of objects (even if only one ID is found). So in React Native, you'll access the ID viareturnedData[0].idif a match exists.
Quick Notes
- Always wrap async/await code in a
try/catchblock to handle unexpected errors (like the server being down, or a network dropout). - If you're unsure about the structure of
returnedData, log it to the console first—this will help you confirm exactly what keys you need to access.
内容的提问来源于stack exchange,提问作者user11027087
相关产品推荐
相关产品推荐

