Изо всех сил, чтобы получить данные из AWS лямбда-JSON - PullRequest
0 голосов
/ 14 июня 2019

Я работаю над лямбда-проектом и получаю данные из API внутри функции, которая выглядит следующим образом:

{ "Title": "300", "Year": "2006", "Rated": "R", "Released": "09 Mar 2007", "Runtime": "117 min", "Genre": "Action, Fantasy, War", "Director": "Zack Snyder", "Writer": "Zack Snyder (screenplay), Kurt Johnstad (screenplay), Michael B. Gordon (screenplay), Frank Miller (graphic novel), Lynn Varley (graphic novel)", "Actors": "Gerard Butler, Lena Headey, Dominic West, David Wenham", "Plot": "King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C.", "Language": "English", "Country": "USA, Canada, Bulgaria", "Awards": "17 wins & 45 nominations.", "Poster": "https://m.media-amazon.com/images/M/MV5BMjc4OTc0ODgwNV5BMl5BanBnXkFtZTcwNjM1ODE0MQ@@._V1_SX300.jpg", "Ratings": [ { "Source": "Internet Movie Database", "Value": "7.7/10" }, { "Source": "Rotten Tomatoes", "Value": "60%" }, { "Source": "Metacritic", "Value": "52/100" } ], "Metascore": "52", "imdbRating": "7.7", "imdbVotes": "691,774", "imdbID": "tt0416449", "Type": "movie", "DVD": "31 Jul 2007", "BoxOffice": "$210,500,000", "Production": "Warner Bros. Pictures", "Website": "http://300themovie.warnerbros.com/", "Response": "True" }

Я пробовал точечную нотацию, индексирую все виды, но независимо от того, что я пытаюсь,Журнал консоли только выходит с

2019-06-14T18:33:46.394Z ecc5d247-6475-464e-8dd7-bec310d98c4a INFO undefined 

У кого-нибудь еще была такая же проблема с lambda и lex?

Спасибо

const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
 let test;

    http.get(url, res => {
      res.setEncoding("utf8");
      let body = "";
      res.on("data", data => {
        body += data;
      });
      res.on("end", () => {
       console.log(body);
        reply = JSON.parse(body);

      });
    });

Это в настоящее время производит отличнохороший JSON в консоли, но на самом деле ничего извлечь невозможно.Я пытался ответить. Год, ответ ["Год"], ответ. [0]. Почти любую комбинацию, которую я могу придумать.

Полный код

'use strict';
'use fetch';


// Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled ("Thanks, your pizza will arrive in 20 minutes")
function close(sessionAttributes, fulfillmentState, message) {
    return {
        sessionAttributes,
        dialogAction: {
            type: 'Close',
            fulfillmentState,
            message,
        },
    };
}

// --------------- Events -----------------------

function dispatch(intentRequest, callback) {
    console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
    const sessionAttributes = intentRequest.sessionAttributes;
    //const film = intentRequest.currentIntent.film;
    const film = intentRequest.currentIntent.slots.film.toString();
    console.log(intentRequest.currentIntent.slots.film.toString());



const https = require('https')
let url = "http://www.omdbapi.com/?t=300&r&apikey=3ecc35a"
let reply;
const http = require('http')
 let test;

    http.get(url, res => {
      res.setEncoding("utf8");
      let body = "";
      res.on("data", data => {
        body += data;
      });
      res.on("end", () => {
       console.log(body);
        reply = JSON.parse(body);

      });
    });



    //const rating = reply.imdbRating;
    console.log(reply);


    callback(close(sessionAttributes, 'Fulfilled',
    {'contentType': 'PlainText', 'content': `The film ${film} has a rating of `}));

}

// --------------- Main handler -----------------------

// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
    try {
        dispatch(event,
            (response) => {
                callback(null, response);
            });
    } catch (err) {
        callback(err);
    }
};

1 Ответ

0 голосов
/ 15 июня 2019

Я попытался воспроизвести проблему с этим кодом и получил следующую ошибку

Response:
{
  "errorType": "TypeError",
  "errorMessage": "Cannot read property 'name' of undefined",
  "trace": [
    "TypeError: Cannot read property 'name' of undefined",
    "    at dispatch (/var/task/index.js:20:112)",
    "    at Runtime.exports.handler (/var/task/index.js:65:9)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:63:25)",
    "    at process._tickCallback (internal/process/next_tick.js:68:7)"
  ]
}

Строка 20 для index.js для меня:

console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);

Однако при использовании тестасобытие в вопросе event.currentIntent не существует, и свойство name объекта события также не существует.

Если я удаляю часть оператора console.log и изменяю его, ссылаясь на атрибут Title, который существует в тестовом событии, я получаю:

console.log(`request received for Title=${intentRequest.Title}`);

INFO request received for Title=300

Похоже, код функции нормально ссылается на атрибуты, но функция просто не получает ожидаемые объекты событий.

HTH

-James

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...