action-on-google api.ai не отправляет тело в запросе POST с помощью nodejs и экспресс

Я пытаюсь запустить пример sillyNameMaker из действий- в Google с помощью api.ai, на моем компьютере. Я настроил сервер nodejs с экспрессом и туннелированием ngrok. Когда я пытаюсь отправить запрос с помощью своего агента на api.ai, мой сервер получает запрос POST, но тело выглядит пустым. Есть ли что-то, что я не настроил должным образом?

Вот мой файл index.js:

'use strict';
var express = require('express')
var app = express()
const ApiAiAssistant = require('actions-on-google').ApiAiAssistant;

function sillyNameMaker(req, res) {
  const assistant = new ApiAiAssistant({request: req, response: res});

  // Create functions to handle requests here
  const WELCOME_INTENT = 'input.welcome';  // the action name from the API.AI intent
  const NUMBER_INTENT = 'input.number';  // the action name from the API.AI intent
  const NUMBER_ARGUMENT = 'input.mynum'; // the action name from the API.AI intent

  function welcomeIntent (assistant) {
    assistant.ask('Welcome to action snippets! Say a number.');
  }

  function numberIntent (assistant) {
    let number = assistant.getArgument(NUMBER_ARGUMENT);
    assistant.tell('You said ' + number);
  }

  let actionMap = new Map();
  actionMap.set(WELCOME_INTENT, welcomeIntent);
  actionMap.set(NUMBER_INTENT, numberIntent);
  assistant.handleRequest(actionMap);

  function responseHandler (assistant) {
    console.log("okok")
    // intent contains the name of the intent you defined in the Actions area of API.AI
    let intent = assistant.getIntent();
    switch (intent) {
      case WELCOME_INTENT:
        assistant.ask('Welcome! Say a number.');
        break;

      case NUMBER_INTENT:
        let number = assistant.getArgument(NUMBER_ARGUMENT);
        assistant.tell('You said ' + number);
        break;
    }
  }
  // you can add the function name instead of an action map
  assistant.handleRequest(responseHandler);
}


app.post('/google', function (req, res) {
  console.log(req.body);
  sillyNameMaker(req, res);
})


app.get('/', function (req, res) {
  res.send("Server is up and running.")
})


app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

И ошибка, которую я получил:

TypeError: Cannot read property 'originalRequest' of undefined
    at new ApiAiAssistant (/Users/clementjoudet/Desktop/Dev/google-home/node_modules/actions-on-google/api-ai-assistant.js:67:19)
    at sillyNameMaker (/Users/clementjoudet/Desktop/Dev/google-home/main.js:8:21)

Я пытаюсь напечатать req.body, но он не определен... Заранее спасибо за помощь.


person jood    schedule 21.04.2017    source источник


Ответы (1)


И вы, и пакет action-on-google делаете предположения о том, как вы используете Express. По умолчанию Express не заполняет атрибут req.body (см. ссылка на req.body). Вместо этого для этого используется дополнительное ПО промежуточного слоя, такое как body-parser.

Вы должны иметь возможность добавить анализатор тела в свой проект с помощью

npm install body-parser

а затем используйте его для анализа тела запроса в JSON (который API.AI отправляет и использует действия в Google) с некоторыми дополнительными строками сразу после того, как вы определяете app для присоединения его к Express:


var bodyParser = require('body-parser');
app.use(bodyParser.json());
person Prisoner    schedule 21.04.2017