【发布时间】:2021-12-17 01:08:07
【问题描述】:
我想使用 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 的解决方案吗?
【问题讨论】:
-
附带说明,您可能希望自己熟悉 SOLID 原则。
-
如果您使用
await,请删除所有.then()。使用旧的类似 Promise 的语法 (.then()) 或新的async/await,不要同时使用。另外,请define "it's not working"?您是否尝试过console.log()的东西,看看您的函数是否被调用以及数据是否正确?控制台中的任何错误?等等。 -
我认为您不需要
qs.stringify()。我不太确定[incodeHeader]: incodeToken,部分。请再次阅读the docs。 -
哈,以前你打电话给
request.post,现在你打电话给axios.get。它应该是axios.post。您不能使用 GET 发送数据对象。
标签: javascript node.js react-native axios xmlhttprequest