javascript - 如何将 request-promise 迁移到 axios 或 fetch
问题描述
我想用 React-Native 编写一个应用程序,它从一个带有 cookie 身份验证的网站加载 JSON 文件。为了测试,我在没有 React-native 和 request-promise 的普通 JS 文件中尝试了它。
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。
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 的解决方案吗?
解决方案
首先,我不知道您为什么要在第一个请求中对请求正文进行字符串化,axios 已经处理了这个,您可以只传递data
对象,也许这是您问题的解决方案。
第二(只是一个提示)。创建一个帮助器对象来发出 http 请求并且不直接实例化 axios,因此,您可以以一种简单的方式更改 http 请求处理程序,而不是在每个文件上更改它,有一天您可能需要这样做,如果您想保留您的应用已更新。
三、不要混和await
,then
选择:
try {
const result = await action();
// ...
} catch (err) {
// ...
}
或者
action()
.then((result) => {
// ...
})
.catch((err) => {
// ...
});
推荐阅读
- xamarin.forms - 如何用不同的颜色绘制选择的项目?
- angular - 如何在Angular7的不同选项卡中导航回上一个路线/页面?
- amazon-web-services - AWS Cloudfront 自定义错误页面是否很慢?
- node.js - 检查电子邮件是否存在续集(节点js)的正确方法?
- python - 在 Python/Kivy 应用程序中保存用户名和密码
- sas - SAS 按组求和,然后为每个组创建新变量
- assembly - 如何正确将此字节值存储在内存中?
- sql-server - 在 Azure DevOps 管道上生成 SQL Server 架构更改脚本
- python - 如何在保留标题的同时翻转 csv 行顺序?
- android - ConstraintLayout.connect() 的 margin 参数是像素还是 dp?