You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:54:00