首页 > 解决方案 > 如何将 node js 客户端库与 express 一起使用?

问题描述

我在不使用节点 js 客户端库的情况下实现了一个 dialogFlow 实现。我一直在手动解析请求并准备响应。现在,我想开始使用 node js 客户端库,如下所示:https ://actions-on-google.github.io/actions-on-google-nodejs/

我正在使用 express 生成器生成的 express 框架。这是我的 app.js 的一些内容:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var smarthome5 = require('./routes/smarthome5');
app.set('view engine', 'jade');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/smarthome5',smarthome5);
module.exports = app;

我的 ./routes/smarthome5 包含这些:

const express = require('express')
var router = express.Router();
const {dialogflow} = require('actions-on-google')

const dfApp = dialogflow()
router.post('/', dfApp)

// Register handlers for Dialogflow intents
dfApp.intent('Default Welcome Intent', conv => {
  conv.ask('Hi, how is it going?')
  conv.ask(`Here's a picture of a cat`)
})

// Intent in Dialogflow called `Goodbye`
dfApp.intent('Goodbye', conv => {
  conv.close('See you later!')
})

dfApp.intent('Default Fallback Intent', conv => {
  conv.ask(`I didn't understand. Can you tell me something else?`)
})

module.exports = router;

但是,当我运行代码并向 /smarthome5 发出 POST 请求时,我收到如下错误:

SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (<anonymous>)
at new User (/app/node_modules/actions-on-google/dist/service/actionssdk/conversation/user.js:75:43)
at new Conversation (/app/node_modules/actions-on-google/dist/service/actionssdk/conversation/conversation.js:73:21)
at new DialogflowConversation (/app/node_modules/actions-on-google/dist/service/dialogflow/conv.js:38:9)
at Function.<anonymous> (/app/node_modules/actions-on-google/dist/service/dialogflow/dialogflow.js:113:24)
at Generator.next (<anonymous>)
at /app/node_modules/actions-on-google/dist/service/dialogflow/dialogflow.js:22:71
at new Promise (<anonymous>)
at __awaiter (/app/node_modules/actions-on-google/dist/service/dialogflow/dialogflow.js:18:12)
at Function.handler (/app/node_modules/actions-on-google/dist/service/dialogflow/dialogflow.js:84:16)

当我尝试用这个替换 ./routes/smarthome5 中的后处理程序时:

router.post('/', function(req, res, next) {
    console.log('POST ' + __filename);
    console.dir(req.body, {depth: null});
})

我能够看到 POST 请求。所以我的路线正在运行,只是我不知道我是否正确使用了 dfApp。

示例发布请求正文和错误

请求正文 1

原始检测意图请求

标题

用户存储字段

标签: expressactions-on-google

解决方案


Actions-On-Google NodeJS 客户端的 Github 页面显示了构建代理的不同方法。还有一个代码片段显示了使用 Express 开发 webhook。在此处查看自述文件。这一切都被覆盖了。



在这里更新

你有它

'use strict';

const {dialogflow} = require('actions-on-google');
const express = require('express');
const bodyParser = require('body-parser');

const app = dialogflow();

app.intent('Default Welcome Intent', conv => {
    conv.ask('Hi, Welcome to Assistant by Express JS ');
});

express().use(bodyParser.json(), app).listen(8080);

推荐阅读