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

使用node-fetch登录Spring登录表单失败,请求排查代码问题

Spring Security 登录的NodeJS实现问题

我可通过浏览器使用用户名和密码访问Spring应用,现希望通过NodeJS应用实现登录。参考《How to login to a spring security login form using cURL?》一文后,已成功用cURL和Postman实现登录,但在NodeJS中实现时遇到问题,尝试过用cookieJar自动管理Cookie仍未解决。

我的实现步骤大致如下:

  • 请求登录页面获取CSRF和SESSIONID令牌
  • 使用这些令牌和身份信息发起登录请求
  • 登录过程中会发生重定向,理论上会返回新的SESSIONID和CSRF令牌,但我的脚本收到了第二个Set-cookie响应,而浏览器登录时不会出现这种情况
  • 尝试使用新令牌请求API,但无法获取数据

以下是我编写的代码,有人能帮我找出问题所在吗?

const extractTokens = (r: any): [string, string] => {
  const csrf = r.headers.get('x-csrf-token')!
  const cookie = r.headers.get('set-cookie')?.split(';')[0]
  return [csrf, cookie]
}

const ping = async () => {
  return fetch('https://lap.drc.ngo/login/root', {
    keepalive: true,
    credentials: 'include',
    method: 'GET',
  })
}

const login = async ([csrf, session]: [string, string]) => {
  return await fetch('https://lap.drc.ngo/j_spring_security_check', {
    keepalive: true,
    credentials: 'include',
    method: 'POST',
    headers: {
      'Cookie': session,
      Authorization: 'Basic ' + btoa(`email:password`)
    },
    body: new URLSearchParams({_csrf: csrf,})
  })
}

const getData = async ([csrf, session]: [string, string]) => {
  return fetch('https://lap.drc.ngo/admin/msd/get-list-data', {
    keepalive: true,
    credentials: 'include',
    method: 'POST',
    headers: {'X-CSRF-TOKEN': csrf, 'Cookie': session},
  })
}

(async () => {
  const pingRes = await ping()
  const loginRes = await login(extractTokens(pingRes))
  await getData(extractTokens(loginRes))
})()

内容的提问来源于stack exchange,提问作者Alexandre Annic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:57:46