我正在使用AWS Lambda通过传递查询参数(例如vendorId)来创建一个获取API,但在某些情况下,我需要整个数据而不传递查询参数,在这种情况下,我的代码是坏的。让我知道如何处理查询参数。
var mysql=require('mysql'); //Require whatever connector you need.
function getConnection()
{
var params={
host : 'myhostinfo',
user : 'myuser',
password : 'mypwd',
database : 'mydb'
};
return mysql.createConnection(params);
}
//This is your handler.
exports.handler=function(event, context,callback)
{
//This is declared inside the handler: it is guaranteed to never be reused!.
var connection=getConnection();
var fetchvendors="";
if(event.query.vendorid)
{
var vendorid=parseInt(event.query.vendorid);
fetchvendors="SELECT v.*,c.vcategoryname FROM `tbl_vendors` v LEFT
OUTER JOIN tbl_demo_categories c ON v.vendorcatid=c.vcategoryid WHERE
v.vendorid="+vendorid;
}
else{
fetchvendors="SELECT v.*,c.vcategoryname FROM `tbl_vendors` v LEFT
OUTER JOIN tbl_demo_categories c ON v.vendorcatid=c.vcategoryid WHERE
status=1";
}
connection.query(fetchvendors, function (error, results, fields) {
if (error) {
connection.destroy();
throw error;
} else {
// connected!
callback(null, results);
connection.end();
}
});
}
这是结果
Response:
{
"errorMessage": "RequestId: 42fd18b1-598c-4f7e-b93b-
b146777772b2
Process exited before completing request"
}
Request ID:
"42fd18b1-598c-4f7e-b93b-b146777772b2"
Function Logs:
START RequestId: 42fd18b1-598c-4f7e-b93b-b146777772b2 Version:
$LATEST
2019-04-04T10:48:34.959Z 42fd18b1-598c-4f7e-b93b-
b146777772b2 TypeError: Cannot read property 'vendorid' of
undefined
4条答案
按热度按时间z9ju0rcb1#
如果您使用API Gateway作为lambda函数的触发器,那么查询参数可以在
event.queryStringParameters
中找到。因此,如果vendorid是GET参数,那么您应该使用event.queryStringParameters.vendorid
。下面是API Gateway Proxy请求Lambda的完整示例。9udxz4iz2#
你应该像这样预先检查对象和它的键是否存在:
4jb9z9bj3#
试试这个-
q8l4jmvw4#
我知道这一个是旧的,但对我来说,它的工作时,我使用以下
注意?.运算符,因为查询字符串中可能不存在
vendorid