我想使用下面与 API Gateway 集成的 AWS Lambda 函数来调用 2 个不同的路由。请查看下面的代码以了解该实现:
import axios from 'axios';
export const handler = async (event) => {
try {
if (event.path === '/countries') {
const countriesResponse = await axios.get('https://countriesnow.space/api/v0.1/countries/states');
const countryNames = countriesResponse.data.data.map(country => country.name);
return {
statusCode: 200,
body: JSON.stringify(countryNames),
};
} else if (event.path === '/states') {
const { country } = JSON.parse(event.body);
const statesResponse = await axios.post('https://countriesnow.space/api/v0.1/countries/states', { country });
const stateNames = statesResponse.data.data.states.map(state => state.name);
return {
statusCode: 200,
body: JSON.stringify(stateNames),
};
} else {
console.log(event.path);
return {
statusCode: 400,
body: JSON.stringify({ message: 'Invalid endpoint' })
};
}
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal Server Error' })
};
}
};
我希望能够在
/countries
上调用 GET 以返回我调用的 API 返回的所有国家/地区。我还希望能够在 /states
上调用 POST 以返回所提供国家/地区的所有州。具体来说,我希望能够进行以下 API 调用:
POST ENDPOINT: `https://api-id.execute-api.region.amazonaws.com/develop/states`
BODY: {"country":"Canada"}
目前,当我这样做时,我得到:
{
"statusCode": 400,
"body": "{\"message\":\"Invalid endpoint\"}"
}
这告诉我,由于某种原因,端点没有被正确命中。这是为什么?我已确认端点
\states
和 \countries
位于 API 网关中。它们在 API 调用和代码中似乎也匹配。但也许我遗漏了一些东西,而且我没有正确使用 event.path
。
如有任何帮助,我们将不胜感激!
尝试记录事件对象并查看其中发生了什么(还将其添加到问题中以便我们可以进一步检查)。它可能有
/develop/states
而不是 /states
。如果 develop
类似于前缀,而您不想使用它,那么您可以尝试使用 event.resourcePath
来代替。