Create actions-on-google object from Express request

梦想与她 提交于 2021-02-08 07:19:16

问题


The documentation here shows this code example for creating an Actions SDK object for Express:

const express = require('express');
const bodyParser = require('body-parser');

const expressApp = express().use(bodyParser.json());
expressApp.post('/fulfillment', app);
expressApp.listen(3000);

But I need to do something like this:

const express = require('express');
const bodyParser = require('body-parser');

function func (req, res) {
    let headers = req.headers;
    let body = req.body;

    console.log(headers);
    console.log(body);

    const app = actionssdk({
        // init: () => body
        // init: () => req
    });

    app.intent('actions.intent.MAIN', (conv) => {
        conv.ask("Welcome to the app");
    })
    return app;
}

const expressApp = express().use(bodyParser.json());
expressApp.post('/fulfillment', func);
expressApp.listen(3000);

This obviously isn't the correct syntax and it doesn't return any response to the Google Action.

The reason I want to do something like this is to initialize the actionssdk object with dynamic clientId. I can extract the projectId from the authorization header present in req.headers object. From the projectId I can dynamically fetch the clientId and initialize the actionssdk by passing the clientId

What would be the correct syntax for this?


回答1:


The app variable can be called with express request and response objects like so, as it is a function:

const express = require('express');
const bodyParser = require('body-parser');

const expressApp = express().use(bodyParser.json());
expressApp.post('/fulfillment', async (req, res) => {
  const clientId = // Some logic to get client ID
  const app = actionssdk({ clientId })
  // Define intent handlers here
  return app(req, res)
});
expressApp.listen(3000);


来源:https://stackoverflow.com/questions/61409333/create-actions-on-google-object-from-express-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!