AngularJS调用FlightAware API遇Authorization跨域错误的解决咨询
Why This Happens
That error you're seeing boils down to the browser's Cross-Origin Resource Sharing (CORS) rules. When your AngularJS app tries to send a request with an Authorization header (which happens automatically with basic auth), the browser first sends an OPTIONS "preflight" request to check if the server allows that header. If FlightAware's server doesn't include Authorization in its Access-Control-Allow-Headers response, the browser blocks the actual request to enforce security.
Also, a critical warning: hardcoding your API key and username directly in frontend code is a massive security risk. Anyone can inspect your app's source code or network traffic to steal those credentials, which could lead to unauthorized use of your FlightAware account.
The Recommended Fix: Use a Backend Proxy
The safest and most reliable way around this is to set up a simple backend proxy (using your existing Node.js code as a starting point). Your AngularJS app will send requests to your own backend server, and your backend will handle the call to FlightAware's API. This avoids CORS issues entirely and keeps your sensitive credentials hidden.
Step 1: Add Proxy Endpoints to Your Node.js Server
Here's how to extend your Node.js code with Express to act as a proxy (I'll use express and cors packages for simplicity):
const express = require('express'); const Client = require('node-rest-client').Client; const cors = require('cors'); const app = express(); // Allow cross-origin requests from your AngularJS app app.use(cors()); app.use(express.json()); // FlightAware API setup (keep this secure on your backend!) const username = 'x'; const apiKey = 'y'; const fxmlUrl = 'https://flightxml.flightaware.com/json/FlightXML3/'; const clientOptions = { user: username, password: apiKey }; const client = new Client(clientOptions); // Register your FlightAware methods like before client.registerMethod('findFlights', `${fxmlUrl}FindFlight`, 'GET'); client.registerMethod('weatherConditions', `${fxmlUrl}WeatherConditions`, 'GET'); // Proxy endpoint for weather conditions app.get('/api/weather', (req, res) => { const airportCode = req.query.airport_code; const requestArgs = { parameters: { airport_code: airportCode } }; client.methods.weatherConditions(requestArgs, (data, response) => { res.json(data.WeatherConditionsResult.conditions[0]); }); }); // Proxy endpoint for flight searches app.get('/api/flights', (req, res) => { const { origin, destination, type } = req.query; const requestArgs = { parameters: { origin, destination, type } }; client.methods.findFlights(requestArgs, (data, response) => { res.json(data); }); }); // Start the proxy server const PORT = 3000; app.listen(PORT, () => { console.log(`Proxy server running on http://localhost:${PORT}`); });
Step 2: Update Your AngularJS Code to Call the Proxy
Now your AngularJS app can request data from your own backend without dealing with auth or CORS:
// Example AngularJS controller angular.module('FlightApp', []) .controller('FlightController', ['$http', function($http) { const vm = this; vm.getHobbyWeather = function() { $http.get('http://localhost:3000/api/weather', { params: { airport_code: 'KHOU' } }).then(response => { console.log('Current conditions at Hobby Airport:', response.data); }).catch(error => { console.error('Failed to fetch weather:', error); }); }; vm.searchFlights = function() { $http.get('http://localhost:3000/api/flights', { params: { origin: 'KIAH', destination: 'KJFK', type: 'nonstop' } }).then(response => { console.log('Found flights:', response.data); }).catch(error => { console.error('Failed to fetch flights:', error); }); }; }]);
Why You Should Avoid Frontend-Only Workarounds
You might be tempted to look for ways to bypass CORS directly in the browser, but don't waste your time. FlightAware's FlightXML API is designed for server-side use, so they almost certainly won't allow Authorization headers in cross-origin requests from browsers. Even if you found a way to hide your credentials temporarily, they'd still be exposed to anyone who knows how to use browser dev tools—this is a major security no-no.
Stick with the backend proxy approach: it's secure, fixes the CORS error, and aligns with how FlightAware expects their API to be used.
内容的提问来源于stack exchange,提问作者Tomasz

