Search code examples
node.jscurlaxiosethereumsmartcontracts

Trying to repliate curl -c post/get with axios in node.js


Doing some Ethereum/Chainlink work and trying to pull some gas price info from the API endpoints on my Chainlink node. Works with curl but I'm having trouble with the cookie using axios in node.js.

First I POST to get the cookie

curl -c cookiefile \
  -d '{"email":"[email protected]", "password":"password"}' \
  -X POST -H 'Content-Type: application/json' \
   http://localhost:6688/sessions

Then get the data like so:

curl -b cookiefile http://localhost:6688/v2/config

Here's my axios code that's supposed to be equivalent. Trying to POST, store the cookie, then GET, but the GET fails auth. POST seems to return the requested "set-cookie" field fine.

const axios = require('axios').default;

const instance = axios.create({
  baseURL: 'http://localhost:6688/v2/config',
  timeout: 1000,
  headers: {'Content-Type': 'application/json'}
});

_getGasPrice()

function _getGasPrice() {
axios.post('http://localhost:6688/sessions', {
    email: 'email',
    password: 'pass'
  })
  .then(function (response) {
    const cookie = response.headers["set-cookie"];
    console.log(cookie);
    instance.defaults.headers.Cookie = cookie;
    axios.get('http://localhost:6688/v2/config'}
    .then(function (repsonse) {
      console.log(response.data.attributes.ethGasPriceDefault);
    })
    .catch((err) => {
      console.log(err);
    })
  })
  .catch((err) => {
    console.log(err);
  })
}

Any help is appreciated, thanks.


Solution

  • const axios = require('axios').default;
    _getGasPrice()
    function _getGasPrice() {
    axios.post('http://localhost:6688/sessions', {
        email: 'email',
        password: 'password',
        headers: {'Content-Type': 'application/json'}
      })
      .then(function (response) {
        const cookie = response.headers["set-cookie"];
        console.log(response);
        axios.get('http://localhost:6688/v2/config', {headers: {Cookie: cookie}})
        .then(function (response) {
          let data = Object.keys(response.data).map(i => response.data[i])
          console.log(data[0].attributes.ethGasPriceDefault);
        })
        .catch((err) => {
          console.log(err);
        })
      })
      .catch((err) => {
        console.log(err);
      })
    }
    

    This wound up working, saving the cookie then passing it in the header of the GET request. Also the format of the GET response was an [object] rather than JSON which I needed to remap in order to get the attribute I wanted.