Authenticating Amadeus Test Flight Api With Javascript Fetch

535 Views Asked by At

I am having issues with testing of Amadeus Flight-Offers Api. Authentication

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2021-02-01&returnDate=2021-02-05&adults=1&max=3. (Reason: header ‘authentication’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).

This is my code

"use_strict";
function getPlane(){
    let url = "https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2021-02-01&returnDate=2021-02-05&adults=1&max=3";
    fetch(url,{
        method:"GET",
        headers:{
            "Content-Type":"application/vnd.amadeus+json",
            "Authentication":"Bearer code here"
        },
        mode:"cors",
        catch:"default"
    }).then(function(response){
        if(response.ok){
            return response.json();
        }else{
            throw new Error(error);
        }
    }).then(function(data){
        console.log(data);
        //query data here
        document.getElementById("flight").insertAdjacentHTML('afterbegin',data.data[0].itineraries[0].segments[0].operating.carrierCode)
    }).catch(function(error){
        console.log(error);
    });
}

getPlane();
1

There are 1 best solutions below

1
On

The Amadeus Self-Service API calls must contain the Authorization HTTP header with the value Bearer access_token, using the access token you have generated. In your code you add Authentication instead of Authorization. Also, the Content-Type is necessary only when you request the access token. Refer to the authorization guide for more information.

    "use_strict";
    function getPlane(){
        let url = "https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2021-02-01&returnDate=2021-02-05&adults=1&max=3";
        fetch(url,{
            method:"GET",
            headers:{
            "Authorization": "Bearer ACCESS_TOKEN_HERE",
            },
            mode:"cors",
            catch:"default"
        }).then(function(response){
            if(response.ok){
                return response.json();
            }else{
                throw new Error(error);
            }
        }).then(function(data){
            console.log(data);
            //query data here
            document.getElementById("flight").insertAdjacentHTML('afterbegin',data.data[0].itineraries[0].segments[0].operating.carrierCode)
        }).catch(function(error){
            console.log(error);
        });
    }

    getPlane();