reactjs 如何将RabbitMQ与React直接连接[副本]

8hhllhi2  于 2023-02-12  发布在  React
关注(0)|答案(1)|浏览(178)
    • 此问题在此处已有答案**:

Rabbit-MQ with React(4个答案)
昨天关门了。
我正在尝试连接rabbitMQ与react,但我无法连接任何帮助
我试过这么多不同的解决方案,但没有用。等待任何解决方案

8dtrkrch

8dtrkrch1#

1.在rabbitmq rabbitmq-plugins enable rabbitmq_web_stomp中启用web套接字
1.运行家兔MQ rabbitmq-service start
React中

import React, { useEffect, useState } from "react";
import Stomp from "stompjs";
export default function Messages() {
  const [sinput, setsInput] = useState("");
  var ws = new WebSocket("ws://127.0.0.1:15674/ws");
  var client = Stomp.over(ws);

  const [msg, setmsg] = useState([]);
  var on_connect = function () {
    console.log("connected");
    client.subscribe("/topic/sender", (messages) => {
      console.log(messages);
      msg.push(messages.body);
      console.log(msg);
      setmsg([...msg]);
    });
  };
  const handleClick = () => {
    console.log(client.subscriptions);
    client.send("/topic/sender",{redelivered: false,},document.getElementById("mess").value);
  };

  var on_error = function () {
    console.log("error");
  };
  useEffect(() => {
    client.connect("guest", "guest", on_connect, on_error, "/");
  });

  return (
    <div>
      <div>Messenger</div>
      <input id="mess" />
      <button onClick={() => {handleClick();}}>send</button>
      {msg.map((val, key) => {
        return <div key={key}>{val}</div>;
      })}
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.1/umd/react-dom.production.min.js"></script>

相关问题