[英]How to migrate request-promise to axios or 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();
这很有效,所以我想在我的应用程序中使用这种方法,但是我找不到在 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 的解决方案吗?
将await axios.get
更改为await axios.post
首先,我不知道你为什么在第一个请求中对请求体进行字符串化,axios 已经处理了这个,你可以只传递data
对象,也许它是你问题的解决方案。
第二(只是一个提示)。 创建一个 helper 对象来发出 http 请求并且不要直接实例 axios,因此,您可以以一种简单的方式更改 http 请求处理程序,而不是在每个文件上更改它,如果您想保留,有一天您可能需要这样做您的应用已更新。
第三,不要混用await
和then
,选择:
try {
const result = await action();
// ...
} catch (err) {
// ...
}
或者
action()
.then((result) => {
// ...
})
.catch((err) => {
// ...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.