大家好,我正在使用 Node js 来使用对话流聊天机器人,我正在尝试从 http 请求 post 方法中获取参数我为此使用了 postman,是的,我确实在标头中将内容类型设置为 json,我的请求正文有以下代码:{"text":"hello"}和以下链接 http://localhost:5000/api/df_text_query我有以下 index.js 文件:const express = require('express');const bodyParser = require('body-parser');const app = express();require('./routes/dialogFlowRoutes')(app);app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }))app.get('/',(req , res)=>{res.send({'hello':'Johnny'});});const PORT = process.env.port || 5000;app.listen(PORT);这是我的dialogflowRoutes.js 文件:const dialogflow = require('dialogflow'); const config = require('../config/keys'); const sessionClient = new dialogflow.SessionsClient(); const sessionPath = sessionClient.sessionPath(config.googleProjectID, config.dialogFlowSessionID); module.exports = app => { app.get('/', (req, res) => { res.send({ 'hello': 'world!' }) }); app.post('/api/df_text_query', async (req, res) => { console.log(req.body) const request = { session: sessionPath, queryInput: { text: { text: req.body.text, languageCode: config.dialogFlowSessionLanguageCode } } }; let responses = await sessionClient .detectIntent(request); res.send(responses[0].queryResult) });app.post('/api/df_event_query', (req, res) => { res.send({ 'do': 'event query' })});}这是我发送以下请求时收到的错误dialogFlowRoutes.js:17 text: req.body.text, ^TypeError: Cannot read property 'text' of undefined
1 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
初始化中间件的顺序很重要。
在对 body 进行操作之前,您必须对其进行解析。初始化 bodyParser 后移动路由中间件,如下所示:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
require('./routes/dialogFlowRoutes')(app);
添加回答
举报
0/150
提交
取消