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

POST /serverSide 401错误及请求参数未正常传递问题求助

解决登录请求参数未传递及401错误问题

问题根源分析

  1. 后端接收参数为undefined:前端通过fetch发送的是JSON格式请求体,但后端仅配置了bodyParser.urlencoded中间件,无法解析JSON类型的请求数据,导致req.body为空,进而username和password取到undefined。
  2. 401 Unauthorized错误:由于参数未正确传递,数据库查询用undefined作为条件,匹配不到任何数据,后端返回401状态码——这是验证失败的表现,但根源是参数传递失败。

修复步骤

1. 后端添加JSON请求体解析中间件

在serverSide.js中补充解析JSON格式请求的中间件,让后端能识别前端发送的JSON数据:

// 保留原有的urlencoded解析,新增JSON解析
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // 关键新增行

// 若使用Express 4.16+版本,可直接用内置解析器(无需依赖bodyParser):
// app.use(express.urlencoded({ extended: true }));
// app.use(express.json());

2. 验证参数传递与查询逻辑

修改后重启后端服务,前端发送请求时,后端即可正确获取req.body.username和req.body.password,此时数据库查询会基于真实参数匹配:

  • 若数据库存在对应账号密码,后端返回200状态码,前端弹出匹配成功提示;
  • 若账号密码不匹配,后端返回401状态码,前端弹出错误提示——这属于正常的验证流程。

修改后的完整serverSide.js代码

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { Client } = require('pg');

const app = express();
const port = 3000;

// Enable CORS for all routes
app.use(cors());

// Middleware to parse request body - 同时支持urlencoded和JSON
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // 新增JSON解析

// Database connection configuration
const dbConfig = {
  user: 'postgres',
  password: '1234',
  host: 'localhost',
  port: 5432,
  database: 'BAC_DB',
};

// Create a new PostgreSQL client
const client = new Client(dbConfig);

// Connect to the database
client.connect()
  .then(() => {
    console.log('Connected to PostgreSQL database');

    // Define route for employee login
    app.post('/serverSide', (req, res) => {
      const { username, password } = req.body;
      console.log('Received username:', username);
      console.log('Received password:', password);

      // Check the database for the provided username and password
      client.query('SELECT * FROM employee WHERE username = $1 AND password = $2', [username, password], (err, result) => {
        if (err) {
          console.error('Error executing query', err);
          res.status(500).send('Internal Server Error');
        } else {
          if (result.rows.length > 0) {
            // Username and password match, send success response
            res.status(200).json({ success: true });
          } else {
            // Username or password is incorrect, send error response
            res.status(401).json({ success: false, message: 'Username or Password is incorrect -- server side' });
          }
        }
      }); 
    }); 

    // Start the server
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
  })
  .catch((err) => {
    console.error('Error connecting to PostgreSQL database', err);
  });

额外注意事项

  • 确保前端fetch请求的Content-Type已设置为application/json,当前代码中已正确配置;
  • 数据库employee表的username、password字段需与前端参数名称一致,数据类型匹配;
  • 生产环境禁止明文存储密码,建议使用bcrypt等工具对密码哈希加密后存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:02:51