我想用React-Native编写一个应用程序,它从具有cookie身份验证的网站加载JSON文件。为了测试,我在一个普通的JS文件中尝试了它,没有使用React-native和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();这很有效,所以我想在我的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中工作的另一个解决方案?
发布于 2021-11-02 13:59:43
将await axios.get更改为await axios.post
发布于 2021-11-02 13:59:49
首先,我不知道为什么你要在第一个请求中把请求主体串起来,axios已经处理这个了,你可以只传递data对象,也许这就是你的问题的解决方案。
第二个(只是一个提示)。创建一个helper对象来发出http请求,并且不直接实例化axios,因此,您可以以一种简单的方式更改http请求处理程序,而不是在每个文件上更改它,如果您想让您的应用程序保持更新,总有一天您可能需要这样做。
第三,不要把await和then混为一谈,选择:
try {
const result = await action();
// ...
} catch (err) {
// ...
}或
action()
.then((result) => {
// ...
})
.catch((err) => {
// ...
});https://stackoverflow.com/questions/69811545
复制相似问题