我想用 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 中有效的解決方案嗎?提前致謝。
uj5u.com熱心網友回復:
更改await axios.get為await axios.post
uj5u.com熱心網友回復:
首先,我不知道你為什么在第一個請求中對請求體進行字串化,axios 已經處理了這個,你可以只傳遞data物件,也許它是你問題的解決方案。
第二(只是一個提示)。創建一個輔助物件來發出 http 請求并且不要直接實體 axios,因此,您可以以一種簡單的方式更改 http 請求處理程式,而不是在每個檔案上更改它,如果您想保留,有一天您可能需要這樣做您的應用已更新。
三、不要混用await和then,選擇:
try {
const result = await action();
// ...
} catch (err) {
// ...
}
或者
action()
.then((result) => {
// ...
})
.catch((err) => {
// ...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345100.html
標籤:javascript 节点.js 反应原生 公理 xmlhttp请求
上一篇:如何映射嵌套物件
下一篇:如何讓元素重新出現?
