NodeJS环境下Lambda跨调用:请求头传递与路径指定问题
Got it, let's break down how to fix both of your issues—since you’re already successfully invoking the myapp-goals-get Lambda from GoalsFeed, we just need to adjust how you pass data in the invocation payload to handle headers and the specific path.
1. Send Headers and Target Path in the Invocation Payload
When calling one Lambda from another using the AWS.Lambda SDK, you can package any custom data (like headers and your desired path) into the Payload parameter. Here’s a Node.js example for your GoalsFeed Lambda:
const AWS = require('aws-sdk'); const lambda = new AWS.Lambda(); exports.handler = async (event) => { // Define parameters for invoking the target Lambda const invokeParams = { FunctionName: 'myapp-goals-get', // Exact name of your target Lambda InvocationType: 'RequestResponse', // Use 'Event' for async calls if needed Payload: JSON.stringify({ // Pass your custom request headers here headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-auth-token', // Replace with actual header values 'X-Custom-Header': 'your-custom-value' }, // Specify the exact path you want to target targetPath: '../owner/123' }) }; try { const lambdaResponse = await lambda.invoke(invokeParams).promise(); // Parse and return the target Lambda's response return JSON.parse(lambdaResponse.Payload); } catch (error) { console.error('Failed to invoke target Lambda:', error); throw error; } };
2. Update the Target Lambda to Use the Passed Data
Your myapp-goals-get Lambda needs to read the headers and path from the incoming payload, then route to the correct logic. You have two options depending on how the target Lambda was originally built:
Option A: Custom Payload Parsing (Simpler for Direct Invocations)
Modify myapp-goals-get to extract the headers and path from the payload directly:
exports.handler = async (event) => { // Parse incoming payload (for direct Lambda invocations, event is the raw payload object) const { headers, targetPath } = event; // Route logic based on the target path let response; switch (targetPath) { case '../owner/123': response = await fetchOwnerGoals(123, headers); break; case '/myapp/goals': response = await fetchAllGoals(headers); break; case '/myapp/goals/1': response = await fetchSingleGoal(1, headers); break; default: return { statusCode: 404, body: JSON.stringify({ message: 'Invalid path requested' }) }; } return { statusCode: 200, headers: headers, // Optionally pass headers back in the response body: JSON.stringify(response) }; }; // Example business logic functions async function fetchOwnerGoals(ownerId, headers) { // Add your actual data fetching logic here (e.g., query DynamoDB) return { ownerId, goals: ['Q3 Fitness Goal', 'Q4 Project Goal'] }; } async function fetchAllGoals(headers) { /* ... */ } async function fetchSingleGoal(goalId, headers) { /* ... */ }
Option B: Mimic API Gateway Event (For Minimal Changes)
If your target Lambda was originally built to handle API Gateway events, you can send a mock API Gateway structure in the payload so it works without major edits:
// In GoalsFeed Lambda, adjust the invokeParams Payload Payload: JSON.stringify({ headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token' }, path: '/myapp/goals/owner/123', // Use the full path here httpMethod: 'GET', // Add any other API Gateway event fields your target Lambda expects (e.g., queryStringParameters) })
Your target Lambda can then use its existing logic that reads from event.path and event.headers—no need to rewrite the routing!
Quick Sanity Check
Double-check that your GoalsFeed Lambda has the lambda:InvokeFunction permission for the myapp-goals-get function in its IAM policy (you likely already have this since invocations are working, but it’s good to confirm).
内容的提问来源于stack exchange,提问作者Lypheus

