【问题标题】:Express server posting twice, exactly two minutes apart?快递服务器发帖两次,正好相隔两分钟?
【发布时间】:2019-12-23 01:34:18
【问题描述】:

我正在尝试使用快速服务器和推送器构建一个反应聊天框来监听对话流机器人。一开始它工作得很好,但机器人总是第二次响应,在两分钟后重复自己(但有时会有不同的响应)到第二次。

我在服务器代码中有一些日志语句来尝试调试它,并且一直在监视反应前端的网络活动。看起来 react 只发送了一个 fetch 请求,因为浏览器中只有一个网络日志。但是在服务器端,请求被记录了两次。我不确定这是为什么或我做错了什么!

// server.js
require("dotenv").config({ path: "variables.env" });

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const processMessage = require("./process-message");

const app = express();

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

app.post("/chat", (req, res) => {
  const { message } = req.body;
  processMessage(message);
  console.log(message);
});

app.set("port", process.env.PORT || 5000);
const server = app.listen(app.get("port"), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});








//process-message.js

const Dialogflow = require("dialogflow");
const Pusher = require("pusher");

const projectID = "firstchatbox-fakeURL";
const sessionID = "123456";
const languageCode = "en-US";

const config = {
  credentials: {
    private_key: process.env.DIALOGFLOW_PRIVATE_KEY,
    client_email: process.env.DIALOGFLOW_CLIENT_EMAIL
  }
};

const pusher = new Pusher({
  appId: process.env.PUSHER_APP_ID,
  key: process.env.PUSHER_APP_KEY,
  secret: process.env.PUSHER_APP_SECRET,
  cluster: process.env.PUSHER_APP_CLUSTER,
  encrypted: true
});

const sessionClient = new Dialogflow.SessionsClient(config);

const sessionPath = sessionClient.sessionPath(projectID, sessionID);

const processMessage = message => {
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: message,
        languageCode
      }
    }
  };

  sessionClient
    .detectIntent(request)
    .then(responses => {
      console.log(responses);
      const result = responses[0].queryResult;
      return pusher.trigger("bot", "bot-response", {
        message: result.fulfillmentText
      });
    })
    .catch(err => {
      console.error("ERROR:", err);
    });
};

module.exports = processMessage;






// Here is the React front-end code, even though i'm ~60% sure 
//the bug is server-side at this point

//App.js



import React, { Component } from "react";
import Pusher from "pusher-js";
import "./App.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userMessage: "",
      conversation: []
    };
  }

  componentDidMount() {
    const pusher = new Pusher("fakepusherappID454564564566", {
      cluster: "us3"
    });

    const channel = pusher.subscribe("bot");
    channel.bind("bot-response", data => {
      const msg = {
        text: data.message,
        user: "ai"
      };
      this.setState({
        conversation: [...this.state.conversation, msg]
      });
    });
  }

  handleChange = event => {
    this.setState({ userMessage: event.target.value });
  };

  handleSubmit = event => {
    event.preventDefault();
    if (!this.state.userMessage.trim()) return;

    const msg = {
      text: this.state.userMessage,
      user: "human"
    };

    this.setState({
      conversation: [...this.state.conversation, msg]
    });

    fetch("http://localhost:5000/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        message: this.state.userMessage
      })
    })
      .then(d => console.log(d))
      .catch(e => console.log(e));

    this.setState({ userMessage: "" });
  };

  render() {
    const ChatBubble = (text, i, className) => {
      return (
        <div key={`${className}-${i}`} className={`${className} chat-bubble`}>
          <span className="chat-content">{text}</span>
        </div>
      );
    };

    const chat = this.state.conversation.map((e, index) =>
      ChatBubble(e.text, index, e.user)
    );

    return (
      <div>
        <h1>React Chatbot</h1>
        <div className="chat-window">
          <div className="conversation-view">{chat}</div>
          <div className="message-box">
            <form onSubmit={this.handleSubmit}>
              <input
                value={this.state.userMessage}
                onInput={this.handleChange}
                onChange={this.handleChange}
                className="text-input"
                type="text"
                autoFocus
                placeholder="Type your message and hit Enter to send"
              />
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default App;

它偶尔会显示控制台错误:

源映射错误:类型错误:尝试获取资源时出现网络错误。

资源网址:http://localhost:3000/static/js/0.chunk.js

源地图网址:0.chunk.js.map

但我认为它们不相关?

【问题讨论】:

  • 为什么在收到 POST 请求时没有从服务器发回任何响应。所有请求都应该发送某种类型的响应。
  • 那么简单地添加“ res.send() ”就可以解决这个问题?我现在正在尝试,它似乎已经解决了这个问题!为什么它需要响应?
  • 我不知道这是否是唯一的问题,但需要解决。
  • 它不仅修复了这个错误,还修复了另一个似乎与前端滚动有关的错误。谢谢!
  • 酷。很高兴它奏效了。我将此建议纳入下面的答案。

标签: node.js reactjs express dialogflow-es pusher


【解决方案1】:

恰好相隔两分钟听起来可能是浏览器请求超时并且浏览器正在重试。

而且,现在我查看了您的 app.post() 处理程序,您似乎没有向客户端发送任何类型的响应,因此可能会导致这样的问题。

您的服务器收到的所有 http 请求都必须发送某种响应,即使它们只是返回 404 或 500 状态。要么做res.sendStatus(200)要么res.send("some response");。

您可以在 Chrome 中打开调试器并查看网络选项卡,然后提交您的表单并准确查看客户端和服务器之间发生的网络流量。

而且,由于您尝试了此操作并解决了您的问题,因此我将其发布为答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 2015-01-27
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多