Home > Blockchain >  How to migrate request-promise to axios or fetch
How to migrate request-promise to axios or fetch

Time:11-03

I want to code a app with React-Native which loads JSON-files from a website with cookie-authentication. For testing I tried it in a normal JS-file without React-native and with request-promise.

const fs = require("fs");
const request = require("request-promise").defaults({ jar: true });

async function main() {
  var incodeHeader = "";
  var incodeToken = "";

  try {
    const loginResult = await request.post("https://somepage/login.php", {
      form: {
        client: "XXX",
        login: "username",
        password: "password",
      },
    });
  } catch (err) {
    console.log(err);
  }

  incodeHeader = getIncodeHeader();
  incodeToken = getIncodeToken();

  const data = await request.post("https://somepage/load.json", {
    headers: {
      [incodeHeader]: incodeToken,
    },

    form: {
      max: "10",
    },
  });

  fs.writeFileSync("data.json", data);
}

main();

This worked well, so I wanted to use this method in my App, but I couldn't find a way to use request-promise in React-Native so I decided to use axios.

const axios = require("axios");
const qs = require("qs");
axios.defaults.withCredentials = true;

async function main() {
  const data = {
    client: "XXX",
    login: "username",
    password: "password",
  };

  await axios
    .post("https://somepage/login.php", qs.stringify(data))
    .catch((err) => console.log(err));

  const incodeHeader = getIncodeHeader();
  const incodeToken = getIncodetoken();

  await axios
    .get(
      "https://somepage/load.json",
      { data: { max: "5" } },
      {
        headers: {
          [incodeHeader]: incodeToken,
        },
      }
    )
    .then((respone) => console.log(respone))
    .catch((err) => console.log(err));
}

main();

But in this code not even the login works and I really don't know why. Can somebody tell me how to do this right, or can tell me another solution which works in React-Native?

CodePudding user response:

change await axios.get to await axios.post

CodePudding user response:

First, I don't know why you're stringifying the request body in the first request, axios already handle this, you can pass just the data object, maybe it's the solution for your problem.

Second (just a tip). Create a helper object to make http requests and do not instance axios directly, so then, you can change the http request handler in an easy way instead changing it on each file, one day you probably will need to do this if you want to keep your app updated.

Third, don't mix await and then, choose:

try {
  const result = await action();

  // ...
} catch (err) {
  // ...
}

or

action()
  .then((result) => {
    // ...
  })
  .catch((err) => {
    // ...
  });
  • Related