简体   繁体   中英

How to migrate request-promise to axios or fetch

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?

await axios.get更改为await axios.post

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) => {
    // ...
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM