如何从Open-Sky Network获取数据?代码无法获取数据且页面未渲染问题咨询
Let’s walk through fixing your code and addressing the common issues that might be blocking your data retrieval.
Step 1: Fix the Obvious Syntax Error
Your useState declaration has a typo—remove the extra = sign to initialize your state properly:
const [flights, setFlights] = useState(null); // Corrected line
Step 2: Resolve CORS Restrictions
If you’re running this code in a browser (like a React app), you’re almost certainly hitting a CORS policy error. The OpenSky Network API doesn’t allow direct cross-origin requests from frontend applications. Here’s how to fix this:
Use a backend proxy: Set up a simple server to forward requests from your frontend to the OpenSky API. This avoids CORS issues because the request originates from the server, not the browser.
Example Node.js proxy with Express:
// server.js const express = require('express'); const fetch = require('node-fetch'); const app = express(); app.get('/api/flights', async (req, res) => { try { const response = await fetch('https://opensky-network.org/api/states/all'); const data = await response.json(); res.json(data); } catch (err) { res.status(500).json({ error: err.message }); } }); app.listen(3001, () => console.log('Proxy running on port 3001'));Then in your React app, fetch from your proxy endpoint instead:
http://localhost:3001/api/flights
Step 3: Add Authentication (Optional but Recommended)
Anonymous requests to OpenSky have strict rate limits (10 requests per minute). To get higher limits (30 requests per minute), authenticate with your OpenSky username and password. Never hardcode credentials in frontend code—keep them in your proxy:
// Inside your proxy's /api/flights route const username = 'your_opensky_username'; const password = 'your_opensky_password'; const auth = btoa(`${username}:${password}`); const response = await fetch('https://opensky-network.org/api/states/all', { headers: { 'Authorization': `Basic ${auth}` } });
Step 4: Proper Error Handling & State Update
Add error catching to handle network issues, and update your state once data is fetched:
const [flights, setFlights] = useState(null); const [error, setError] = useState(null); useEffect(() => { const fetchFlights = async () => { try { const res = await fetch('http://localhost:3001/api/flights'); if (!res.ok) { throw new Error(`HTTP error! Status: ${res.status}`); } const data = await res.json(); console.log(data); setFlights(data); // Update state with fetched data } catch (err) { setError(err.message); console.error('Failed to fetch flights:', err); } }; fetchFlights(); }, []);
Step 5: Fix Page Rendering Issues
Prevent broken renders by adding conditional logic to handle loading and error states:
if (error) return <div>Error loading flights: {error}</div>; if (!flights) return <div>Loading flight data...</div>; return ( <div> <h1>Live Flight Data</h1> {/* Map over flights.states to render individual flight details */} {flights.states.map((flight, index) => ( <div key={index}> <p>Callsign: {flight[1]?.trim() || 'Unknown'}</p> <p>Origin Country: {flight[2]}</p> </div> ))} </div> );
内容的提问来源于stack exchange,提问作者Ijay

