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

Node.js中Axios保存登录凭证失败,后续请求未携带Cookie

axios设置withCredentials:true后Cookie未携带的问题解决

你的核心问题在于请求数据的序列化方式不符合application/x-www-form-urlencoded格式要求,导致登录请求并未被服务器正确处理(虽然返回了跳转HTML,但实际未生成有效登录Cookie),后续请求自然无法通过身份验证。

原因分析

axios默认会将POST请求的JavaScript对象参数转换为JSON格式发送,但你在headers中指定了Content-Type: application/x-www-form-urlencoded,此时需要将数据序列化为表单格式(key1=value1&key2=value2)才能被服务器正确解析。而superagent会自动处理这种格式的序列化,所以之前用superagent能正常工作。

解决方法

你可以通过两种方式修正数据序列化:

方法1:使用qs库统一处理(推荐)

安装qs库后,在axios实例中配置transformRequest自动序列化数据:

import axios from 'axios'
import qs from 'qs'

const examlpeHost = 'http://radmandemo.dmasoftlab.com'

const axiosInstance = axios.create({
  baseURL: examlpeHost,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  // 自动将请求数据序列化为表单格式
  transformRequest: [function (data) {
    return qs.stringify(data)
  }],
})

// 登录请求(无需手动处理数据)
const loginEnpoint = '/admin.php?cont=login'
const loginRes = await axiosInstance.post(loginEnpoint, {
  managername: 'admin',
  password: '1111',
  md5: '27780bc84ff5136090c9b33063c0d38f',
})

// 创建用户请求(同样无需手动处理)
const createUserEndpoint = '/admin.php?cont=store_user'
const createUserRes = await axiosInstance.post(createUserEndpoint, {
  username: 'test_user123456789',
  password1: '1111',
  password2: '1111',
  srvid: 0,
})

// 后续判断逻辑不变
const loginResHtml = loginRes.data
const isSuccessLogin = loginResHtml.includes(`<META http-equiv="refresh" content="0;URL=admin.php">`)
if (isSuccessLogin) console.log('[success ✅] login successful!')
else throw new Error('[fail ❌] Login failed!')

const createUserResHtml = createUserRes.data
const isSuccessCreateUser = createUserResHtml.includes('Account registered')
if (isSuccessCreateUser) console.log('[success ✅] create user successful!')
else console.log('[fail ❌] create user failed!')

方法2:使用原生URLSearchParams(无需额外安装库)

手动构建表单格式的数据:

import axios from 'axios'

const examlpeHost = 'http://radmandemo.dmasoftlab.com'

const axiosInstance = axios.create({
  baseURL: examlpeHost,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
})

// 登录请求
const loginEnpoint = '/admin.php?cont=login'
const loginData = new URLSearchParams()
loginData.append('managername', 'admin')
loginData.append('password', '1111')
loginData.append('md5', '27780bc84ff5136090c9b33063c0d38f')

const loginRes = await axiosInstance.post(loginEnpoint, loginData)

// 创建用户请求
const createUserEndpoint = '/admin.php?cont=store_user'
const createUserData = new URLSearchParams()
createUserData.append('username', 'test_user123456789')
createUserData.append('password1', '1111')
createUserData.append('password2', '1111')
createUserData.append('srvid', 0)

const createUserRes = await axiosInstance.post(createUserEndpoint, createUserData)

// 后续判断逻辑不变

验证要点

修正后,登录请求会被服务器正确处理并返回有效Cookie,withCredentials: true会自动存储并在后续请求中携带该Cookie,从而通过身份验证。

内容的提问来源于stack exchange,提问作者Islam Y-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:10:39