SqlError:位置1的参数未定义问题排查求助
问题分析与解决方案
问题出在前端fetchData函数的请求URL构造上:你把[startDate, endDate]直接拼进URL路径,这种写法会将数组转为逗号分隔的字符串(例如/api/get-canceled/2018-01-01%2000:00:00,2022-08-15%2000:00:00),但后端是从req.query中读取startDate和endDate字段——这两个字段根本不存在,导致SQL查询时参数变为undefined,触发了SqlError: Parameter at position 1 is undefined。
1. 修正前端axios参数传递方式
将路径拼接改为用params传递查询参数,确保后端能正确获取到startDate和endDate:
const fetchData: any = async () => { // 跳过初始空值场景,避免无效请求 if (!startDate || !endDate) return; const response: any = await axios.get('/api/get-canceled', { params: { startDate, endDate } }); let dataRows: any[] = response.data; console.log('response', response.data); setRows(dataRows); };
2. 优化初始渲染逻辑(可选)
原useEffect会在组件挂载时(此时startDate和endDate为空字符串)发起无效请求,可增加判断条件:
useEffect(() => { if (startDate && endDate) { fetchData(); } }, [startDate, endDate]);
3. 后端增加参数校验与响应优化(可选)
在后端代码中先校验参数是否存在,避免SQL报错;同时修正res.json的使用方式:
import type { NextApiRequest, NextApiResponse } from 'next'; import * as pool from '../../../src/utils/dbConnection'; import console from 'console'; export default async (req: NextApiRequest, res: NextApiResponse) => { const { startDate, endDate }: any = req.query; // 参数校验 if (!startDate || !endDate) { return res.status(400).json({ error: 'startDate和endDate参数不能为空' }); } let conn; try { conn = await pool.getConnection(); const rows = await conn.query( `SELECT oi.po, oi.id, p.product_id, p.vendor_id, oi.quantity, oi.scanned_qty, oi.order_id, oi.qty_canceled, oi.channel_order_item_id, o.order_datetime, o.ship_lastname, o.ship_firstname, o.ship_email, o.channel_order_id, o.channel_order_id_alt, o.channel_id, p.description, p.stock_status FROM shopper s INNER JOIN orders o on s.id = o.shopper_id INNER JOIN orderitems oi ON o.id = oi.order_id INNER JOIN products p ON oi.item_id = p.id WHERE o.order_datetime > ? AND o.order_datetime < ? AND oi.qty_canceled > 0;`, [startDate, endDate] ); res.status(200).json(rows); // res.json会自动序列化对象,无需手动JSON.stringify } catch (err) { console.log(err); res.status(500).json({ error: '查询失败' }); // 返回错误响应,方便前端捕获 } finally { if (conn) conn.end(); } };
内容的提问来源于stack exchange,提问作者Blake Lucey
相关产品推荐
相关产品推荐

