![](/img/trans.png)
[英]Create my own mvc structure with node.js, express and use restful api
[英]What is my correct url path to the API restful with node.js & express
我的restful api中有两条路由,带有node.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;
当我用 query 替换 query2 时:
const id2 = req.query.id2;
我看到没有错误的空 aladinModelStations "",但我 100% 确定我输入 id2=1010 的位置 - 应该有数据。
我不确定如何正确,因为我在第一条路线中有查询,在第二条路线中有 query2?
从我的第二条路径查看 api 值的正确路径是什么?
你的代码有const id2 = req.query2.id2;
对于路线/stations
但它应该是const id2 = req.query.id2;
. 因为在req
对象中没有任何名为query2
的属性。 因此,您会收到该错误,因为req.query2
本身是未定义的,并且您无法从未定义的值中获取id2
值。 因此错误:
类型错误:无法读取未定义的属性“id2”
1.
您必须使用req.query
:
此属性是一个对象,其中包含路由中每个查询字符串参数的属性。 如果没有查询字符串,则为空对象 {}。
2.
当我用 query 替换 query2 时:
const id2 = req.query.id2;
我看到空的 aladinModelStation "" 没有错误,
如果您查看已设置的第一条路线aladinModel
: aladinModel = result
,您必须对aladinModelStations
执行相同的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)}`;
变量aladinModelStations
未分配给result2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.