【发布时间】:2017-11-03 13:20:18
【问题描述】:
我正在学习 node js,并且正在使用 Dialogflow 开发机器人。我想建立一个简单的机制:
- 第 1 步:dialogflow 发送带有 param1 参数的 POST 请求
- 第 2 步:我的应用程序通过 JSON 形式的 POST 响应返回一条等待消息(例如:“您的请求正在处理中”)
- 第 3 步:我从 REST API 检索数据
- 第 4 步:使用 JSON 响应 DialogFlow 的 Webhood
我的问题(第 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()
但它没有用。感谢您的帮助!
【问题讨论】:
-
为什么不连接 2 个响应并发送最终响应?
-
您不能使用 HTTP 向单个请求发送多个响应,这是协议的基本概念之一:一个请求,一个响应。处理请求需要多长时间(得到最终结果)?您如何提交请求(新页面加载或 Ajax)?
-
是的,谢谢您的回答。问题是数据提取需要超过 5 秒,如果我的机器人在 1 秒内没有收到数据,它会返回错误(我无法在 DialogFlow 级别修改计时器)。我不知道如何设置异步处理以通过另一种方式发送第二个响应。
标签: javascript json node.js express dialogflow-es