JERRY_LIU 2025-05-28 17:44 采纳率: 83.3%
浏览 12
已结题

nodejs express 传递参数出错

写了两个后端的代码,在网页中调用正常,但是写了一个前面页面来调用,一直报错。

/db/index.js档案,数据库配置

const config = {
      server: '192.168.2.4',
      database: 'database',
      user: 'sa',
      password: 'xxxxxxxx',
      port: 1433,
      options: {
        trustedConnection: true,
      },
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000,
      },
      options: {
        encrypt: false,
      },
    };
module.exports = {
   config 
  // 输出数据库配置
};

start.js档案, 连接mssql , 并执行查询:


```javascript
const express = require('express');
const sql = require('mssql');
const str = require('./db/index'); 

// 创建Express应用
const app = express();

const sqlScript = 'Select column1, column2, column3  From table where id = @id'
// 连接数据库
sql.connect(str.config).then(() => {
  console.log('数据库连接成功');
  //跨域资源共享
  
 
  // 定义API路由
  app.get('/api/data/:id', (req, res) => {
    // 执行SQL查询
    new sql.Request()
    .input('id', req.params.id)//接收Api参数,传递给sqlScript参数@id
    .query(sqlScript)
      .then(result => {
        // 将查询结果返回给API
        res.json(result.recordset);
      })
      .catch(err => {
        // 错误处理
        console.error('SQL查询错误:', err);
        res.status(500).send({ message: 'Server error' });
      });
  });
 

  // 监听端口
  const port = 3000;
  app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
  });
}).catch(err => {
  console.error('数据库连接失败:', err);
});



在cmd 窗口中执行node start.js,启动后端服务,然后在浏览器中输入网址:
http://localhost:3000/api/data/198  
198是ID值,此时可以正常返回数据库的查询内容。
如果把网址改为:http://localhost:3000/api/data?id=198 ,此时返回 Cannot GET /api/data

不知道是哪里写错了,有没有高手帮忙看一下。谢谢!
  • 写回答

6条回答 默认 最新

  • 檀越@新空间 2025-05-28 17:45
    关注

    下午好🌅🌅🌅
    本答案参考通义千问

    问题的核心在于你定义的API路由 /api/data/:id 使用了 路径参数req.params.id),而当你访问 http://localhost:3000/api/data?id=198 时,URL 的查询字符串部分并没有被解析为路径参数。

    分析问题原因

    1. 路由匹配机制

      • 路径参数(如 /api/data/:id)通过 req.params.id 获取,这是基于 URL 的路径部分。
      • 查询字符串(如 ?id=198)则需要通过 req.query.id 来获取。
    2. 你的代码只支持路径参数

      • 在路由定义中,app.get('/api/data/:id', ...) 只会匹配类似 /api/data/198 的请求。
      • 当你访问 http://localhost:3000/api/data?id=198 时,路由不会匹配到,因此返回 Cannot GET /api/data

    解决方案

    我们需要调整代码以支持两种方式:路径参数和查询字符串参数。以下是详细的解决方案:


    修改后的代码

    const express = require('express');
    const sql = require('mssql');
    const str = require('./db/index');
    
    // 创建Express应用
    const app = express();
    
    const sqlScript = 'SELECT column1, column2, column3 FROM table WHERE id = @id';
    
    // 连接数据库
    sql.connect(str.config).then(() => {
      console.log('数据库连接成功');
      
      // 定义API路由,支持路径参数和查询字符串参数
      app.get('/api/data/:id', (req, res) => {
        const id = req.params.id; // 优先使用路径参数
        executeQuery(id, res);
      });
    
      app.get('/api/data', (req, res) => {
        const id = req.query.id; // 如果路径参数不存在,则使用查询字符串参数
        if (!id) {
          return res.status(400).send({ message: 'Missing "id" parameter' });
        }
        executeQuery(id, res);
      });
    
      // 执行SQL查询的通用函数
      function executeQuery(id, res) {
        new sql.Request()
          .input('id', sql.Int, id) // 设置SQL参数类型为整数
          .query(sqlScript)
          .then(result => {
            // 返回查询结果
            res.json(result.recordset);
          })
          .catch(err => {
            // 错误处理
            console.error('SQL查询错误:', err);
            res.status(500).send({ message: 'Server error' });
          });
      }
    
      // 监听端口
      const port = 3000;
      app.listen(port, () => {
        console.log(`服务器运行在 http://localhost:${port}`);
      });
    }).catch(err => {
      console.error('数据库连接失败:', err);
    });
    

    关键点解释

    1. 支持两种参数来源

      • 路径参数:通过 req.params.id 获取。
      • 查询字符串参数:通过 req.query.id 获取。
    2. 通用查询函数

      • 将查询逻辑封装在一个独立的函数 executeQuery 中,避免重复代码。
    3. 参数类型设置

      • 使用 sql.Int 明确指定 SQL 参数类型,避免潜在的类型错误。
    4. 错误处理

      • 如果查询字符串中缺少 id 参数,返回 400 Bad Request 响应。

    测试

    1. 使用路径参数:

      http://localhost:3000/api/data/198
      
      • 正常返回数据库查询结果。
    2. 使用查询字符串参数:

      http://localhost:3000/api/data?id=198
      
      • 同样正常返回数据库查询结果。
    3. 缺少 id 参数:

      http://localhost:3000/api/data
      
      • 返回 400 Bad Request 响应。

    总结

    通过上述修改,你的 API 路由现在可以同时支持路径参数和查询字符串参数。这种设计更加灵活,能够满足不同客户端的需求。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 6月6日
  • 已采纳回答 5月29日
  • 创建了问题 5月28日