我在带有node的restful api中有两个路由.js和express。
第一条路线是:
http://localhost:8000/?date=2019-10-20&id=4&daysForward=3
并且工作正常!
我尝试查看来自第二条路线的数据,但看到此错误:
TypeError: Cannot read property 'id2' of undefined
当我输入此网址时:
http://localhost:8000/stations?id2=1010
代码:
app.route('/stations')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
const id2 = req.query.id2;
const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells WHERE Station=${id2}`;
con.query(query2, function (err, result2, fields) {
if (err)
return res.status(500).json({ error: "Internal server error"})
aladinModelStations = result2;
res.json({ aladinModelStations })
})
});
所以我认为错误就在这一行:
const id2 = req.query2.id2;
当我用查询替换查询 2 时:
const id2 = req.query.id2;
我看到空的 aladinModelStation " 没有错误,但我 100% 确定我在哪里输入 id2=1010 - 应该有数据。
我不确定如何正确,因为我在第一条路线中有查询,在第二条路线中有查询 2?
从我的第二条路径查看 api 上的值的正确路径是什么?
1.
您必须使用req.query
:
此属性是一个对象,其中包含路由中每个查询字符串参数的属性。如果没有查询字符串,则为空对象 {}。
阿拉伯数字。
当我用查询替换查询 2 时:
const id2 = req.query.id2;
我看到空的 aladin模型站 " 没有 erros,
如果你看你设置的第一条路线aladinModel
:aladinModel = result
,你必须对aladinModelStations
做同样的事情:
const aladinModelStations = result2;
res.json({ aladinModelStations })
或
res.json({ aladinModelStations: result2 })
3.
如req.query
的文档和@sol的评论中所述,您永远不应该相信用户输入
由于 req.query 的形状基于用户控制的输入,因此此对象中的所有属性和值都是不受信任的,应在信任之前进行验证。
例如,您可以使用connection.escapeId()
对其进行转义:
const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells WHERE Station=${connection.escapeId(id2)}`;
您的代码已const id2 = req.query2.id2;
路由/stations
,但它应该是const id2 = req.query.id2;
。因为req
对象中没有任何名为query2
的属性。因此,您会收到该错误,因为req.query2
本身是未定义的,并且您无法从未定义的值中获取id2
值。因此错误:
类型错误: 无法读取未定义的属性"id2">
变量aladinModelStations
没有分配result2