2017-04-21 30 views
1

我試圖在我的計算機上運行帶有api.ai的action-on-google上的sillyNameMaker example。 我使用express和ngrok隧道建立了一個nodejs服務器。當我嘗試向api.ai上的我的代理髮送請求時,我的服務器收到POST請求,但主體看起來是空的。有什麼我沒有正確設置?action-on-google api.ai不會在POST請求中發送body與nodejs並快速

這裏是我的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卻是不確定的...在感謝提前尋求你的幫助。

回答

8

你和google-on-action包都在假設你如何使用Express。默認情況下,Express不會而不是填充req.body屬性(請參閱reference for req.body)。相反,它依賴於其他中間件,例如body-parser來這樣做。

你應該能夠身體解析器添加到您的項目,

npm install body-parser 

,然後用它來請求體解析成J​​SON(其中API.AI發送和行動上,谷歌使用),還有一些在定義app以將其附加到Express後,附加行:


var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
+0

非常感謝! – clemkoa