реагировать сокет io и google-maps-реакции роутера в маркере - PullRequest
0 голосов
/ 15 октября 2019

Работа над приложением, которое отображает местоположения пользователей на карте Google и нажатие на маркеры карты, вызывает InfoWindow с чатом, который называется response-router-dom

Вместо этого я получаю ошибку прокси от socket.io [1] Proxy error: Could not proxy request /socket.io/?EIO=3&transport=polling&t=MtE8T3o&sid=nb7zMqkw-AoVs1igAAAV from localhost:3000 to http://127.0.0.1:5000/. [1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

Ниже приведен класс Map.js, и маршрутизатор чата должен открываться в теге InfoWindow

import React, { Component } from "react";
import {Launcher} from 'react-chat-window'
import MessageBox from "./MessageBox"
import MessageArea from "./MessageArea"
import {
  withGoogleMap,
  GoogleMap,
  withScriptjs,
  Marker,
  InfoWindow
} from "react-google-maps";
import { compose, withProps, withStateHandlers } from "recompose";
import glamorous from "glamorous";
import ChatContainerClass from "./ChatContainerClass"
//import Chat from './chatcomps/Chat/Chat';
import Join from './chatcomps/Join/Join';
import { withRouter } from 'react-router-dom';
import { BrowserRouter as Router, Route } from "react-router-dom";
const io = require('socket.io-client');

const MapWithPlaces = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=MYSECRETKEY&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: "100vh", width: "100%" }} />,
    mapElement: <div style={{ height: "100%" }} />
  }),
  withStateHandlers(
    props => ({
      infoWindows: Array.from(props.places).map(p => {
        return { isOpen: false };
      })
    }),
    {
      onToggleOpen: ({ infoWindows }) => selectedIndex => ({
        infoWindows: infoWindows.map((iw, i) => {
          iw.isOpen = selectedIndex === i;
          return iw;
        })
      })
    }
  ),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap defaultZoom={props.zoom} defaultCenter={props.center}>

    {props.places &&
      props.places.map((place, i) => {
        let lat = parseFloat(place.lat, 10);
        let lng = parseFloat(place.lng, 10);

        return (
          <Marker
            id={place.id}
            key={place.id}
            position={{ lat: lat, lng: lng }}
            title={place.from}
            onClick={props.onToggleOpen.bind(this, i)}
            icon="https://img.icons8.com/cotton/64/000000/fishing-hook--v3.png"
            //onClick=<img width='200px' src='./static/profilepics/' + {props.places.profilepic} +''/>
                //<img width='200px' src='./static/profilepics/' + {props.places.profilepic} +''/>
          >
            {props.infoWindows[i].isOpen && (
              <InfoWindow onCloseClick={props.onToggleOpen.bind(i)}>
                <div>
                <img width='200px' src={place.profilepic}/>

                  <Router>
                   <Route path="/" exact component={Join} />
                   <Route path="/chat" component={Chat} />
                  </Router>

                </div>

              </InfoWindow>
            )}

          </Marker>
        );
      })}
  </GoogleMap>
));

export default MapWithPlaces;

Вот код на стороне сервера:

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");

const users = require("./routes/api/users");

const socketIo = require("socket.io");

const http = require("http");
const cors = require('cors');

const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');

const router = require('./router');
const app = express();



// Bodyparser middleware
app.use(
  bodyParser.urlencoded({
    extended: false
  })
);
app.use(bodyParser.json());
app.use(express.static('profilepics'));
app.use('/profilepics', express.static('profilepics'));
app.use(cors());
app.use(router);



// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(
    db,
    { useNewUrlParser: true }
  )
  .then(() => console.log("MongoDB successfully connected"))
  .catch(err => console.log(err));

// Passport middleware
app.use(passport.initialize());

// Passport config
require("./config/passport")(passport);

// Routes
app.use("/api/users", users);
const server = http.createServer(app);
const io = socketIo.listen(server);


io.on('connect', (socket) => {
  socket.on('join', ({ name, room }, callback) => {
    const { error, user } = addUser({ id: socket.id, name, room });

    if(error) return callback(error);

    socket.join(user.room);

    socket.emit('message', { user: 'admin', text: `${user.name}, welcome to room ${user.room}.`});
    socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name} has joined!` });

    io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room) });

    callback();
  });

  socket.on('sendMessage', (message, callback) => {
    const user = getUser(socket.id);

    io.to(user.room).emit('message', { user: user.name, text: message });

    callback();
  });

  socket.on('disconnect', () => {
    const user = removeUser(socket.id);

    if(user) {
      io.to(user.room).emit('message', { user: 'Admin', text: `${user.name} has left.` });
      io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
    }
  })
  socket.on("error", (err) =>
  {
    console.log("Caught server socket error: ");
    console.log(err.stack);
  })
  socket.send('hi there');
});

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

server.listen(port, () => console.log(`Server up and running on port ${port} !`));


console.log('listening on port ', port);
...