我正在学习节点js,我正在使用Dialogflow工作。我想建立一个简单的机制:
我的问题(在第4步)是我无法为同一请求发送两个响应,我有这样的错误消息:
2017-11-03T12:45:00.774506+00:00 app[web.1]: Error: Can't set headers after they are sent.
2017-11-03T12:45:00.774507+00:00 app[web.1]: at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
2017-11-03T12:45:00.774508+00:00 app[web.1]: at ServerResponse.header (/app/node_modules/express/lib/response.js:767:10)
2017-11-03T12:45:00.774508+00:00 app[web.1]: at ServerResponse.send (/app/node_modules/express/lib/response.js:170:12)
2017-11-03T12:45:00.774509+00:00 app[web.1]: at searching.then (/app/index.js:89:21)
2017-11-03T12:45:00.774509+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:109:7)
这是我的代码:
const express = require('express');
const bodyParser = require('body-parser');
//middleware
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/webhook', function (req, res, next) {
if (req.body.result && req.body.result.parameters && req.body.result.parameters.param1) {
// First response
var speechObject = {
speech: "your request is being processed",
displayText: "your request is being processed",
source: 'webhook-nodejs-api'}
var json_1 = JSON.stringify(speechObject)
res.send(json_1)
// Second response
searching_data_from_api().then(() => {
console.log("return second response JSON")
var dataObject = { type_pizza: "4 formages" }
var eventObject = { name: "pizza_est_prete", data: dataObject }
var json_2 = JSON.stringify({
followupEvent: eventObject
})
res.send(json_2);
return res.end()
}).catch(error => {
console.log(error)
})
} else {
var speech = "There is a problem. Try Again"
return res.json({
speech: speech,
displayText: speech,
source: 'webhook-nodejs-api'
})
console.log("There is a problem. Try Again")
}
})
app.listen((process.env.PORT || 8000), function () {
console.log("Server up and listening");
});
我的问题是,我该如何发送第二个答案?我试着用: - res.write(JSON.stringify(data1)) - res.write(JSON.stringify(data2)) - res.end()
但它没有用。谢谢你的帮助!
答案 0 :(得分:0)
您应该查看followup events
基本上,您需要立即响应,然后加载数据,并将它们发布到您的机器人。
请参阅:https://discuss.api.ai/t/fulfilment-using-webhook-takes-time-to-get-the-data/3726/7
答案 1 :(得分:0)
如果您正在使用Dialogflow的内置集成,则只能直接响应用户的输入发出响应,因此无法对单个请求做出两次响应。
如果您决定不使用内置集成,则可以编写一些代码,将原始“您的请求正在处理”的响应发送给用户,执行所需的处理,然后发送后续内容自己回应。您将执行以下操作:
/query
API端点重要的是要注意,您将自己向用户发送最终回复;不会涉及Dialogflow。