NodeJS 如何使用AWS Lambda和API Gateway更正带有event.path的状态400?

kmynzznz  于 8个月前  发布在  Node.js
关注(0)|答案(2)|浏览(105)

我想使用下面与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
基于以下评论的其他错误:
我已经记录了该事件,发现它是以下对象:

{
    "version": "2.0",
    "routeKey": "POST /states",
    "rawPath": "/develop/states",
    "rawQueryString": "",
    "headers": {
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br",
        "cache-control": "no-cache",
        "content-length": "26",
        "content-type": "application/json",
        "host": "cc1sxgjhi4.execute-api.us-east-1.amazonaws.com",
        "postman-token": "848e4596-d42d-4606-b84e-67ce27f05dfa",
        "user-agent": "PostmanRuntime/7.35.0",
        "x-amzn-trace-id": "Root=1-659800b6-5a35109603b2112664c29481",
        "x-forwarded-for": "142.112.6.191",
        "x-forwarded-port": "443",
        "x-forwarded-proto": "https"
    },
    "requestContext": {
        "accountId": "624448452992",
        "apiId": "cc1sxgjhi4",
        "domainName": "cc1sxgjhi4.execute-api.us-east-1.amazonaws.com",
        "domainPrefix": "cc1sxgjhi4",
        "http": {
            "method": "POST",
            "path": "/develop/states",
            "protocol": "HTTP/1.1",
            "sourceIp": "142.112.6.191",
            "userAgent": "PostmanRuntime/7.35.0"
        },
        "requestId": "REUMkjYdIAMEVmQ=",
        "routeKey": "POST /states",
        "stage": "develop",
        "time": "05/Jan/2024:13:14:30 +0000",
        "timeEpoch": 1704460470586
    },
    "body": "{\n  \"country\": \"Canada\"\n}\n",
    "isBase64Encoded": false
}


develop是我在AWS上创建并部署API Gateway的阶段。我已经尝试了POST到https://api-id.execute-api.region.amazonaws.com/develop/stateshttps://api-id.execute-api.region.amazonaws.com/states和GET到https://api-id.execute-api.region.amazonaws.com/develop/countrieshttps://api-id.execute-api.region.amazonaws.com/countries

bpzcxfmw

bpzcxfmw1#

尝试记录事件对象,看看它里面有什么(也把它添加到问题中,这样我们就可以进一步检查)。它可能有/develop/states而不是/states。如果develop类似于前缀,你不想使用它,那么你可以尝试使用event.resourcePath

kq0g1dla

kq0g1dla2#

问题是event.path。我应该在event.rawPath上调用if。下面是完整的更正代码。

import axios from 'axios';

export const handler = async (event) => {
  try {
    console.log('EVENT');
    console.log(JSON.stringify(event, null, 2));
    if (event.rawPath === '/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.rawPath === '/states') {
      const { country } = JSON.parse(event.body);

      const statesResponse = await axios.post('https://countriesnow.space/api/v0.1/countries/states', { country });
      console.log(statesResponse);
      const stateNames = statesResponse.data.data.states.map(state => state.name);

      return {
        statusCode: 200,
        body: JSON.stringify(stateNames),
      };
    } else {
      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' })
    };
  }
};

字符串

相关问题