인프런 커뮤니티 질문&답변

이수경님의 프로필 이미지

작성한 질문수

따라하며 배우는 노드, 리액트 시리즈 - 챗봇 사이트 만들기

챗봇 어플리케이션 만들기#3 구조 설명 & textQuery Route 만들기

postman 에 답이 오지 않습니다.(수정)

24.08.14 14:55 작성

·

52

·

수정됨

0

브라우저를 실행 했습니다

image.png

 

문제는

image.png

이렇게 보내고

image.png

이런 에러가 났습니다.

또한 터미널에는 아무런 값도 뜨지않고

image.png

이상태 그대로 입니다. 무엇이 문제일까요?아래 처럼되지 않습니다.

image.png

<예제가 바르게 작동된 모습> 

const express = require('express');
const router = express.Router();
const structjson = require('./structjson.js');
const dialogflow = require('dialogflow');
const uuid = require('uuid');

const config = require('../config/keys');

const projectId = config.googleProjectID
const sessionId = config.dialogFlowSessionID
const languageCode = config.dialogFlowSessionLanguageCode


// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

// We will make two routes 


// Text Query Route

router.post('/textQuery', async (req, res) => {
    //We need to send some information that comes from the client to Dialogflow API 
    // The text query request.
    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                // The query to send to the dialogflow agent
                text: req.body.text,
                // The language used by the client (en-US)
                languageCode: languageCode,
            },
        },
    };

    // Send request and log result
    const responses = await sessionClient.detectIntent(request);
    console.log('Detected intent');
    const result = responses[0].queryResult;
    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);

    res.send(result)
})



//Event Query Route

router.post('/eventQuery', async (req, res) => {
    //We need to send some information that comes from the client to Dialogflow API 
    // The text query request.
    const request = {
        session: sessionPath,
        queryInput: {
            event: {
                // The query to send to the dialogflow agent
                name: req.body.event,
                // The language used by the client (en-US)
                languageCode: languageCode,
            },
        },
    };

    // Send request and log result
    const responses = await sessionClient.detectIntent(request);
    console.log('Detected intent');
    const result = responses[0].queryResult;
    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);

    res.send(result)
})







module.exports = router;
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();

const config = require("./server/config/keys");
// const mongoose = require("mongoose");
// mongoose.connect(config.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
//   .then(() => console.log('MongoDB Connected...'))
//   .catch(err => console.log(err));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.use('/api/dialogflow', require('./server/routes/dialogflow'));

// Serve static assets if in production
if (process.env.NODE_ENV === "production") {

  // Set static folder
  app.use(express.static("client/build"));

  // index.html for all page routes
  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server Running at ${port}`)
});
{
  "name": "chatbot-app",
  "version": "1.0.0",
  "description": "chatbot-app",
  "main": "index.js",
  "engines": {
    "node": ">=20.16.0",
    "npm": ">=10.2.0"
  },
  "scripts": {
    "start": "node index.js",
    "backend": "nodemon index.js",
    "frontend": "npm run front --prefix client",
    "dev": "concurrently \"npm run backend\" \"npm run start --prefix client\""
  },
  "author": "Jaewon Ahn",
  "license": "ISC",
  "dependencies": {
    "actions-on-google": "^2.6.0",
    "body-parser": "^1.18.3",
    "dialogflow": "^1.2.0",
    "dialogflow-fulfillment": "^0.6.1",
    "express": "^4.16.4",
    "mongoose": "^5.4.20"
  },
  "devDependencies": {
    "concurrently": "^4.1.0",
    "nodemon": "^1.18.10"
  }
}

답변 1

0

인프런 AI 인턴님의 프로필 이미지

2024. 08. 15. 15:01

안녕하세요, 인프런 AI 인턴입니다.

문제를 해결하기 위해 고려해야 할 몇 가지 사항이 있습니다.

  1. 라우트 확인: 제공된 예제코드에 따르면, /api/dialogflow/testQuery 대신 /api/dialogflow/textQuery 또는 /api/dialogflow/eventQuery로 POST 요청을 보내야 합니다. URL을 확인하고 올바른 라우트로 요청을 보내십시오.

  2. 서버 로그 확인: 터미널에 아무것도 출력되지 않는 경우, 서버 코드 내의 로깅 구문(console.log)이 실행되지 않는 것일 수 있습니다. 특히, 에러 핸들링을 위한 로그를 추가하여 어떤 부분에서 문제가 발생하는지 파악할 수 있습니다.

  3. 포스트맨 설정 확인: POST 요청을 보낼 때 Content-Type 헤더가 application/json으로 설정되었는지 확인하십시오. 요청 본문(Body)의 형식이 JSON임을 정확히 명시해야 서버가 올바르게 파싱할 수 있습니다.

  4. 네트워크 문제: 로컬 개발 환경에서 작업하는 경우, 방화벽이나 네트워크 설정이 올바른지 확인해 보아야 할 수도 있습니다. 다른 포트에서 서버를 실행하여 문제가 해결되는지 확인해 볼 수도 있습니다.

  5. 에러 핸들링 코드 추가: 서버 코드에 에러를 catch하고 로그에 기록할 수 있는 에러 핸들링 로직을 추가합니다. 이를 통해 문제의 원인을 좀 더 쉽게 찾을 수 있습니다.

위 사항들을 검토하시고 문제가 계속되면, 서버 로그나 추가적인 정보를 제공해 주시면 더 정확한 해결책을 제시할 수 있습니다.