首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将request-promise迁移到axios或fetch

如何将request-promise迁移到axios或fetch
EN

Stack Overflow用户
提问于 2021-11-02 13:45:44
回答 2查看 281关注 0票数 0

我想用React-Native编写一个应用程序,它从具有cookie身份验证的网站加载JSON文件。为了测试,我在一个普通的JS文件中尝试了它,没有使用React-native和request-promise。

代码语言:javascript
复制
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();

这很有效,所以我想在我的App中使用这个方法,但我找不到在React-Native中使用request-promise的方法,所以我决定使用axios。

代码语言:javascript
复制
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();

但是在这段代码中,甚至连登录都不起作用,我真的不知道为什么。有人能告诉我怎么做对吗,或者能告诉我在React-Native中工作的另一个解决方案?

EN

回答 2

Stack Overflow用户

发布于 2021-11-02 13:59:43

await axios.get更改为await axios.post

票数 0
EN

Stack Overflow用户

发布于 2021-11-02 13:59:49

首先,我不知道为什么你要在第一个请求中把请求主体串起来,axios已经处理这个了,你可以只传递data对象,也许这就是你的问题的解决方案。

第二个(只是一个提示)。创建一个helper对象来发出http请求,并且不直接实例化axios,因此,您可以以一种简单的方式更改http请求处理程序,而不是在每个文件上更改它,如果您想让您的应用程序保持更新,总有一天您可能需要这样做。

第三,不要把awaitthen混为一谈,选择:

代码语言:javascript
复制
try {
  const result = await action();

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

代码语言:javascript
复制
action()
  .then((result) => {
    // ...
  })
  .catch((err) => {
    // ...
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69811545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档