我试图测试我的API调用中是否存在API令牌。传递给的标头是-
"host": [
{
"key": "Host",
"value": "mydomain"
}
],
"x-api-key": [
{
"key": "x-api-key",
"value": "mykey"
}
]
}
现在我的代码看起来像
// Check if apikey is a part of the headers
if ( !headers.hasOwnProperty('x-api-key') || headers['x-api-key'][0].value!="mykey") {
const body = 'Unauthorized';
const response = {
status: 401,
statusDescription: 'Unauthorized',
body: body,
};
callback(null, response);
}
My If case errors out instead of sending 401 if the headers are missing x-api-key
altogether
"errorMessage": "Cannot read property '0' of undefined",
我应该如何更改条件,以便在缺少标题键/值的情况下检查键/值对并且没有未定义的错误
Maybe you can change the
||
to an&&
(OR to an AND).Your first condition checks if
x-api-key
exists in the headers. And the second condition checks the value for thex-api-key
.The way
OR
works is that it will stop its execution either at the first occurence of atrue
condition or will process each condition. Thus in your case, ifx-api-key
is not passed as a header, it still goes and checks the second condition. Since thex-api-key
does not exist, it will not be able to read[0]
of the property and hence the error.However
AND
stops its execution at the first occurence of afalse
condition, and hence will never process the second condition if thex-api-key
is not a part of the headers.