React JS报错:SyntaxError: JSON.parse解析异常求助
Let's break down why you're hitting this error and how to fix it step by step:
1. The Most Likely Culprit: Missing Protocol in Fetch URL
Your React fetch call uses '192.168.1.2:5000' without the http:// prefix. Browsers treat this as a relative path (not an external API endpoint), so it's probably requesting something like http://your-react-app-domain/192.168.1.2:5000 instead of your Flask server. This returns an error page (not valid JSON), hence the parsing failure.
Fix: Update your fetch URL to include the HTTP protocol:
componentDidMount(){ fetch('http://192.168.1.2:5000') // Add http:// here .then( res => res.json() ) .then( (data) => { this.setState({ contacts: data }) console.log(data) }) .catch(err => console.error('Fetch error:', err)) }
2. Resolve Cross-Origin Resource Sharing (CORS) Issue
Since your React app (running on a different port, e.g., 3000) and Flask server (port 5000) are separate origins, browsers block the request by default. Even if your JSON is valid, this can cause the response to be an error instead of your expected data.
Fix: Install and enable CORS in your Flask app:
- First, install the
flask-corspackage:pip install flask-cors - Update your Flask code to enable CORS:
from flask import Flask, jsonify from flask_cors import CORS # Import CORS import pyrebase config = # Your Firebase config here firebase = pyrebase.initialize_app(config) db = firebase.database() app = Flask(__name__) CORS(app) # Enable CORS for all routes @app.route("/") def home(): db_events = db.child().get().val() return jsonify(db_events) if __name__ == "__main__": app.run(host='0.0.0.0', port=5000) # Ensure server listens on all interfaces
3. Verify the Response
After making these changes, open your browser's DevTools (Network tab) and check the request to http://192.168.1.2:5000:
- Confirm the Status Code is 200 OK.
- Check the Response tab to ensure you're getting the valid JSON you shared, not an error page or HTML.
Bonus: Structure Your State Correctly
Looking at your JSON response, the temperature data is nested under DHT11.Temperature. You might want to update your state setup to map this data properly later:
.then( (data) => { this.setState({ contacts: data, temperatures: Object.values(data.DHT11.Temperature) // Extract temperature values }) console.log(data.DHT11.Temperature) })
内容的提问来源于stack exchange,提问作者sagar.p

