Function in logic.js works in playground but not i

2019-08-20 06:34发布

问题:

I have a function in my logic.js file that retrieves the latitude and longitude of a plane from an api:

function getLocation(){

    var url = 'https://opensky-network.org/api/states/all?time=1458564121&icao24=3c6444'

    return fetch(url)             // Call the fetch function passing the url of the API as a parameter
    .then(function(resp){
        data = resp.json()         // Transform the data into json
        return data
    }).then(function(data) {

        lat = data.states[0][5]
        long = data.states[0][6]
        lat = lat.toString()
        long = long.toString()
        location = [lat,long]
        return location
      })
    }
}

when I test this function on the playground it successfully retrieves the latitude and longitude of the plane. However when I try to carry out the same function through the composer REST sever I get the following error:

Error trying invoke business network. Error: No valid responses from any peers.\nResponse from attempted peer comms was an error: Error: chaincode error (status: 500, message: ReferenceError: identifier 'fetch' undefined)

Does anyone know why this is the case?

回答1:

think fetch() is a web browser (library) API, especially if using the web connection with a 'fake' fabric in Playground - whereas its not available in the Composer REST server / runtime looks like (when the transaction in question that calls the function is invoked).

Hyperledger Composer allows you to do call-outs - see more here https://hyperledger.github.io/composer/integrating/call-out

the OpenSky REST APIs can be called from there (and the results returned as JS Objects if possible)

eg. GET /states/all example

var url = "https://opensky-network.org/api/states/all?time=1458564121&icao24=3c6444";

return post( url, postTransaction)
  .then(function (resp) {
// same code as you had before
});

The body property of the response (resp) is automatically converted to a JS Object if possible, otherwise it is returned as a string.