Search code examples
javascriptnode.jsfetchdialogflow-es

node.js fetch post request returning index.html instead of json


I have a node.js app connected to a dialogflow bot I created, in which there's only one file: app.js.

I have index.html, index.js UI for the bot, which when I open unconnected to app.js, runs perfectly. I get json response from app.js However, when I tried to include the UI (index.html and index.js) in app.js, the post method is returning index.html instead of the json it returned before, resulting in error: "SyntaxError: Unexpected token < in JSON at position 0" (because index.html is returned instead of json)

Here's my app.js

    const dialogflow = require('@google-cloud/dialogflow');
    const uuid = require('uuid');
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    const port = 9000;
    const sessionId = uuid.v4();
    
    app.use(bodyParser.urlencoded({
      extended: false
    }));
    
    // ------------------The following code is the one I use for including the UI----------------------------------
    
    const path = require('path');
    app.use(express.static('botui'));
    app.use('/', function(req,res){
      res.sendFile(path.join(__dirname+'/botui/index.html'));
    });
    
    // ------------------------------Code for including the UI ended-----------------------------------------------
    // ------------------When I did not use the above code and just opened file://index.html it worked great-------
    
    app.use(function (req, res, next) {
    
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
      res.setHeader('Access-Control-Allow-Credentials', true);
      
      // Pass to next layer of middleware
      next();
    });
    
    app.post('/send-msg',(req,res)=>{
      runSample(req.body.MSG).then(data=>{
        res.send({
          statusCode: 200,
          body: {},
          headers: {
          'Content-Type': 'application/json', 
          'Access-Control-Allow-Origin': '*' 
      },
        Reply:data})
      })
    })
    /**
     * Send a query to the dialogflow agent, and return the query result.
     * @param {string} projectId The project to be used
     */
    async function runSample(msg, projectId = 'bot_ID') {
      // Create a new session
      const sessionClient = new dialogflow.SessionsClient({
        keyFilename:"BOT-KEY.json"
      });
      const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
    
      // The text query request.
      const request = {
        session: sessionPath,
        queryInput: {
          text: {
            // The query to send to the dialogflow agent
            text: msg,
            // The language used by the client (en-US)
            languageCode: 'en-US',
          },
        },
      };
    
      // 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}`);
      if (result.intent) {
        console.log(`  Intent: ${result.intent.displayName}`);
      } else {
        console.log(`  No intent matched.`);
      }
      return result.fulfillmentText;
    }
    
    app.listen(port,()=>{
      console.log("Running on port: " + port)
    })

And here's the code from index.js which sends the POST request:

    fetch(url, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json', 
        'Access-Control-Allow-Origin': '*' 
    },
      method: 'POST',
      body:data
    })
    .then(res => res.json())
     .then(response => {
      console.log(response);
      serverMessage(response.Reply);     
      
     })
      .catch(error => console.error('Error h:', error));

Solution

  • It seems you should replace app.use('/', function(req,res){ to app.get('/', function(req,res){

    take a look at Difference between app.use and app.get in express.js