我在从数据库请求数据时遇到了SqlError。具体来说,我认为问题出在我的fetchData
函数中;很可能,我没有正确传递两个参数(startDate
和endDate
)。
如文章标题所述,我遇到的SqlError如下:
SqlError: Parameter at position 1 is undefined
此外,请注意,根据我的控制台,这些参数确实有值:
start date: 2018-01-01 00:00:00
end date: 2022-08-15 00:00:00
下面是我的fetchData
函数,以及定义startDate
和endDate
状态的其他辅助函数:
const [startDate, setStartDate]: any = useState('');
const [endDate, setEndDate]: any = useState('');
//Get data from database
useEffect(() => {
fetchData();
}, [startDate, endDate]);
const fetchData: any = async () => {
const response: any = await axios.get(`/api/get-canceled/${[startDate, endDate]}`);
let dataRows: any[] = response.data;
console.log('response', response.data);
setRows(dataRows);
};
const handleStart = (e: any) => {
const inputStart = e.target.value;
setStartInput(inputStart);
const start = `${inputStart} 00:00:00`;
setStartDate(start);
};
console.log(startDate);
const handleEnd = (e: any) => {
const inputEnd = e.target.value;
setEndInput(inputEnd);
const end = `${inputEnd} 00:00:00`;
setEndDate(end);
};
console.log(endDate);
下面是我的API:
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;
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(JSON.stringify(rows));
} catch (err) {
console.log(err);
} finally {
if (conn) conn.end(); // close connection
}
};
任何帮助都是非常感谢的。谢谢!
2条答案
按热度按时间3phpmpom1#
请尝试在前端替换fetchData函数。
umuewwlo2#
在调用axios get方法时,应该使用params对象。