问题
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