簡體   English   中英

node.js 獲取后請求返回索引。html 而不是 json

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

我有一個 node.js 應用程序連接到我創建的對話流機器人,其中只有一個文件:app.js。

我有 index.html,機器人的 index.js UI,當我打開未連接到 app.js 時,它運行完美。 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”(因為返回 index.html 而不是 json)

這是我的 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)
    })

下面是 index.js 中發送 POST 請求的代碼:

    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));

看來您應該將app.use('/', function(req,res){替換為app.get('/', function(req,res){

看看express.js 中 app.use 和 app.get 之間的區別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM