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

Node Express代理登录触发400 Bad Request错误排查求助

问题描述

使用http-proxy-middleware搭建的Node Express代理服务器能正常访问目标登录页面,但登录时返回400 Bad Request错误,直接访问目标页面输入相同凭据可正常登录。另外登录后会进入一个需勾选授权的页面,不确定是否与此问题相关。

代理服务器代码

const express = require('express');
const morgan = require("morgan");
const { createProxyMiddleware } = require('http-proxy-middleware');
// Create Express Server
const app = express();

// Configuration
const PORT = 3000;
const HOST = "localhost";
const API_SERVICE_URL = "https://##authorisationURL&clientid=####etc>”; 
app.use(morgan('dev'));
// Info GET endpoint
app.get('/info', (req, res, next) => {
   res.send('Test');
});
// Proxy endpoints
app.use('/json_placeholder', createProxyMiddleware({
   target: API_SERVICE_URL,
   changeOrigin: true,
   pathRewrite: {
       [`^/json_placeholder`]: '',
   },
}));
// Start the Proxy
app.listen(PORT, HOST, () => {
   console.log(`Starting Proxy at ${HOST}:${PORT}`);
});

调试补充

  • Morgan设为dev模式后,控制台仅输出:
    GET /json_placeholder 302 824 - 798.260 ms
    
  • 登录报错时控制台无额外信息,Chrome开发者工具显示400 Bad Request错误。

解决建议
  1. 修正目标URL格式
    你的API_SERVICE_URL末尾有多余的>符号,这会直接导致请求地址无效,先修正:

    const API_SERVICE_URL = "https://##authorisationURL&clientid=####etc"; // 移除末尾的>
    
  2. 处理POST请求与Cookie转发
    登录请求多为POST方法,代理可能未正确转发请求体或Cookie:

    • 添加Express请求体解析中间件,确保能处理POST数据:
      app.use(express.urlencoded({ extended: true }));
      app.use(express.json());
      
    • 在代理配置中添加Cookie重写与请求体处理:
      app.use('/json_placeholder', createProxyMiddleware({
         target: API_SERVICE_URL,
         changeOrigin: true,
         pathRewrite: {
             [`^/json_placeholder`]: '',
         },
         cookieDomainRewrite: "localhost", // 将目标域名的Cookie重写为本地域名
         onProxyReq: (proxyReq, req, res) => {
             // 处理POST请求体,确保Content-Type和长度正确
             if (req.body && Object.keys(req.body).length) {
                 const bodyData = JSON.stringify(req.body);
                 proxyReq.setHeader('Content-Type', 'application/json');
                 proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
                 proxyReq.write(bodyData);
             }
         }
      }));
      
  3. 跟进302跳转
    登录后的302跳转可能导致代理未正确处理授权页面请求,启用followRedirects:

    app.use('/json_placeholder', createProxyMiddleware({
       // 其他配置...
       followRedirects: true
    }));
    
  4. 捕获详细错误日志
    增强错误监听,获取更具体的报错信息:

    const proxy = createProxyMiddleware({
       // 其他配置...
    });
    app.use('/json_placeholder', proxy);
    
    // 监听代理错误
    proxy.on('error', (err, req, res) => {
        console.error('代理错误详情:', err);
        res.status(500).send('代理请求出错');
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:05:20