如何将request-promise迁移到axios或fetch,适配React-Native带Cookie认证请求
问题排查与修复方案
你现有代码存在以下几处明显错误:
- 登录请求缺失表单提交对应的请求头:用
qs.stringify序列化表单数据后,需要手动指定Content-Type: application/x-www-form-urlencoded,否则服务端会无法识别提交的参数格式 - 第二个请求方法不匹配:原request-promise代码中调用
load.json用的是POST方法,你改写后误用了GET方法 - axios参数传递格式错误:axios的第二个参数为请求体(POST场景)/配置对象(GET场景),你将
data和headers拆分为两个独立参数传入,导致headers配置完全不生效 - GET请求本身不支持通过
data字段传递请求体,即使强行传了服务端也不会解析 - 代码存在拼写错误:获取token的函数名
getIncodetoken大小写不匹配,正确应为getIncodeToken
修正后的axios实现
const axios = require("axios"); const qs = require("qs"); // 注意需要后端CORS配置允许Credentials,否则该配置不生效 axios.defaults.withCredentials = true; async function main() { try { // 1. 执行登录 const loginData = { client: "XXX", login: "username", password: "password", }; await axios.post( "https://somepage/login.php", qs.stringify(loginData), { headers: { "Content-Type": "application/x-www-form-urlencoded" } } ); const incodeHeader = getIncodeHeader(); const incodeToken = getIncodeToken(); // 2. 加载JSON数据,和原逻辑保持一致用POST提交表单 const loadResp = await axios.post( "https://somepage/load.json", qs.stringify({ max: "10" }), { headers: { "Content-Type": "application/x-www-form-urlencoded", [incodeHeader]: incodeToken } } ); console.log(loadResp.data); // React Native环境无法直接使用node的fs模块,如需写入本地可接入react-native-fs库 } catch (err) { console.error("请求出错:", err); } } main();
更适配React Native的替代方案:内置fetch API
不需要引入额外第三方依赖,适配性更强,fetch会自动管理同域Cookie:
const qs = require("qs"); async function main() { try { // 登录请求 await fetch("https://somepage/login.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: qs.stringify({ client: "XXX", login: "username", password: "password" }), credentials: "include" // 自动携带、存储Cookie }); const incodeHeader = getIncodeHeader(); const incodeToken = getIncodeToken(); // 加载JSON请求 const loadResp = await fetch("https://somepage/load.json", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", [incodeHeader]: incodeToken }, body: qs.stringify({ max: "10" }), credentials: "include" }); const data = await loadResp.json(); console.log(data); } catch (err) { console.error(err); } } main();
内容的提问来源于stack exchange,提问作者Matthias
相关产品推荐
相关产品推荐

