Javascript 错误连接拒绝本地主机:5000/用户从其他设备

Javascript 错误连接拒绝本地主机:5000/用户从其他设备,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,我正在尝试制作一个协作白板,其中多个客户端连接到服务器,每个客户端都可以看到每个人在白板上绘制的内容。它的运行方式是:首先,您必须键入terminalnode server.js以执行server.js文件,该文件在localhost:5000上运行。之后,您打开一个新终端,然后键入npm start,它将在localhost:3000上打开React应用程序。 现在的问题是,我的另一个设备告诉我GEThttp://localhost:5000/user net:当我单击inspect时,连接错

我正在尝试制作一个协作白板,其中多个客户端连接到服务器,每个客户端都可以看到每个人在白板上绘制的内容。它的运行方式是:首先,您必须键入terminal
node server.js
以执行server.js文件,该文件在localhost:5000上运行。之后,您打开一个新终端,然后键入
npm start
,它将在localhost:3000上打开React应用程序。 现在的问题是,我的另一个设备告诉我
GEThttp://localhost:5000/user net:当我单击inspect时,连接错误被拒绝
。这是显示MySQL数据库中图片的JSON数据的链接。因此,我无法在不同的设备上看到白板上数据库中的图片。只有在我自己的设备上。但奇怪的是,当我在另一个选项卡中显式键入IP地址、端口和
/user
时,我只能看到JSON数据。但是在白板上,它告诉我这个错误,并且没有显示数据库中的图片

这是server.js代码:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const mysql = require('mysql')
var bodyParser = require('body-parser');
app.use(bodyParser.json({type:'application/json'}));
app.use(bodyParser.urlencoded({extended:true}));
const connection = mysql.createConnection({
      host: "localhost",
      port: "3306",
      user: "root",
      password: "----",
      database: "pictures"
})


connection.connect(function(error){
      if(error) console.log(error);
      else console.log("connected");
});

app.get('/user', function(req, res){
      res.header('Access-Control-Allow-Origin', '*');
      connection.query('select * from pictures', function(error, rows, fields){
            if(error) console.log(error);
    
            else{
                console.log(rows);
                res.send(rows);
    
            }
    
      });
    });

io.on('connection', (socket)=> {
      console.log('User Online');

      socket.on('canvas-data', (data)=> {
            socket.broadcast.emit('canvas-data', data);
            
      })
})

var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
http.listen(server_port, () => {
    console.log("Started on : "+ server_port);
})
这是我的白板的react组件:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Board from '../board/Board';
import DragMove from "../DragMove";
import $ from 'jquery';
import Safe from "react-safe";
import 'jquery-ui-dist/jquery-ui';
import Draggable from 'react-draggable';
import io from 'socket.io-client';
import { Text, View,FlatList} from 'react-native';
import './style.css';


class Container extends React.Component
{
  
    state ={
        userData:[],
        images:[{image:'images/kitten.jpg'}, {image:'images/penguin.jpg'}],
        id: 0
      }
    
      timeout;
      socket = io.connect();
  
      ctx;
      isDrawing = false;
      rect = true;
      image;

      constructor(props) {
        super(props);

        this.socket.on("canvas-data", function(data){

            var root = this;
            var interval = setInterval(function(){
                if(root.isDrawing) return;
                root.isDrawing = true;
                clearInterval(interval);
                var image = new Image()
                var canvas = document.querySelector('#board');
                var ctx = canvas.getContext('2d');
                image.onload = function() {
                    ctx.drawImage(image, 0, 0);
                    
                    root.isDrawing = false;
                };
                image.src = data;
            }, 200)
        })
        
    }
 
    
        async componentDidMount() {
            this.drawOnCanvas();
            const url = "http://localhost:5000/user";
            const response = await fetch(url);
            const data = await response.json(); 
            this.setState({userData: data});
            console.log(this.state.userData);
            var root = this;
            var canvas=document.getElementById("board");
            var ctx=canvas.getContext("2d");
    
            var $canvas=$("#board");
            var Offset=$canvas.offset();
            var offsetX=Offset.left;
            var offsetY=Offset.top;
    
            var x,y,width,height;
    
            var $images=$(".img");
    
            $(function(){
                $images.draggable({
                    helper:'clone',
                });
    
            $images.each(function(index, element){
                $(this).data("imagesIndex", index);
            });
    
            $canvas.droppable({
                drop:dragDrop,
            });
    
            function dragDrop(e, ui){
                x=parseInt(ui.offset.left-offsetX)-1;
                y=parseInt(ui.offset.top-offsetY-125);
                width=ui.helper[0].width;
                height=ui.helper[0].height;
    
                var image = new Image();
                var theIndex=ui.draggable.data("imagesIndex");
                ctx.drawImage($images[theIndex], x, y, width, height);
    
                var tempCanvas=document.createElement('canvas');
                var tempCtx=tempCanvas.getContext('2d');
                tempCanvas.width=width;
                tempCanvas.height=height;
                //tempCtx.drawImage(canvas,x,y,width,height,0,0,width,height);
                var img=new Image();

                img.onload=function(){
                    ctx.drawImage(img, x, y, width, height )
                };
                img.src=tempCanvas.toDataURL();
                console.log(img.src);
               
                $(".img").dblclick(function() {
                    $(this).remove();
                    });     
            }
    
            })
    }

    changeColor(params) {
        this.setState({
            color: params.target.value
        })
    }

    changeSize(params) {
        this.setState({
            size: params.target.value
        })
    }
    




    clickMe(){
        this.rect = true
        alert(this.rect)
    }
 

    componentWillReceiveProps(newProps) {
        this.ctx.strokeStyle = newProps.color;
        this.ctx.lineWidth = newProps.size;
    }

    drawOnCanvas() {
        var canvas = document.querySelector('#board');
        this.ctx = canvas.getContext('2d');
        var ctx = this.ctx;

        var sketch = document.querySelector('#dropHere');
        var sketch_style = getComputedStyle(sketch);
        canvas.width = parseInt(sketch_style.getPropertyValue('width'));
        canvas.height = parseInt(sketch_style.getPropertyValue('height'));

        var mouse = {x: 0, y: 0};
        var last_mouse = {x: 0, y: 0};

        /* Mouse Capturing Work */
        canvas.addEventListener('mousemove', function(e) {
            last_mouse.x = mouse.x;
            last_mouse.y = mouse.y;

            mouse.x = e.pageX - this.offsetLeft;
            mouse.y = e.pageY - this.offsetTop;
        }, false);


        /* Drawing on Paint App */
        ctx.lineWidth = this.props.size;
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';
        ctx.strokeStyle = this.props.color;

        canvas.addEventListener('mousedown', function(e) {
            canvas.addEventListener('mousemove', onPaint, false);
        }, false);

        canvas.addEventListener('mouseup', function() {
            canvas.removeEventListener('mousemove', onPaint, false);
        }, false);

        var root = this;
        var onPaint = function() {
            ctx.beginPath();
            ctx.moveTo(last_mouse.x, last_mouse.y);
            ctx.lineTo(mouse.x, mouse.y);
            ctx.closePath();
            ctx.stroke();

            if(root.timeout != undefined) clearTimeout(root.timeout);
            root.timeout = setTimeout(function(){
                var base64ImageData = canvas.toDataURL("image/png");
                root.socket.emit("canvas-data", base64ImageData);
            }, 1000)
        };
    }

    render() {
    
        return (
            
            <div className="container">
            <div className="tools-section">
                <div className="color-picker-container">
                    Select Brush Color : &nbsp; 
                    <input type="color" value={this.state.color} onChange={this.changeColor.bind(this)}/>
                </div>

                <div className="brushsize-container">
                    Select Brush Size : &nbsp; 
                    <select value={this.state.size} onChange={this.changeSize.bind(this)}>
                        <option> 5 </option>
                        <option> 10 </option>
                        <option> 15 </option>
                        <option> 20 </option>
                        <option> 25 </option>
                        <option> 30 </option>
                    </select>
                </div>

            </div>
    
            <div className="board-container">
                
                
            
                <h4>Select picture!</h4>
            
                    
                        {this.state.userData.map(image => (
                            <div className="dragImg"><img id={"gif"+this.state.id++} className="img" src={image.picture} width='200px' height='100px'/></div>
                            
                        ))}
            
                            
                <div id="dropHere"><canvas className="board" id="board" color={this.state.color} size={this.state.size}></canvas></div>
                
                <button onClick={()=>this.clickMe()}>Click me</button>                            

        
            </div>
        </div>

                    
           
        );
    }

    
}



export default Container
import React,{Component}来自'React';
从“react dom”导入react dom;
从“../Board/Board”导入板;
从“./DragMove”导入DragMove;
从“jquery”导入美元;
从“反应安全”导入安全;
导入“jquery ui dist/jquery ui”;
从“react Draggable”导入Draggable;
从“socket.io客户端”导入io;
从“react native”导入{Text,View,FlatList};
导入“/style.css”;
类容器扩展了React.Component
{
陈述={
用户数据:[],
图片:[{image:'images/kitten.jpg'},{image:'images/penguin.jpg'}],
身份证号码:0
}
超时;
socket=io.connect();
ctx;
isDrawing=false;
rect=true;
形象;
建造师(道具){
超级(道具);
this.socket.on(“画布数据”),函数(数据){
var root=这个;
var interval=setInterval(函数(){
if(root.isDrawing)返回;
root.isDrawing=true;
间隔时间;
var image=新映像()
var canvas=document.querySelector(“#board”);
var ctx=canvas.getContext('2d');
image.onload=函数(){
ctx.drawImage(图像,0,0);
root.isDrawing=false;
};
image.src=数据;
}, 200)
})
}
异步组件didmount(){
这个.drawincanvas();
常量url=”http://localhost:5000/user";
const response=等待获取(url);
const data=wait response.json();
this.setState({userData:data});
log(this.state.userData);
var root=这个;
var canvas=document.getElementById(“board”);
var ctx=canvas.getContext(“2d”);
var$canvas=$(“董事会”);
var Offset=$canvas.Offset();
var offsetX=Offset.left;
var offsetY=Offset.top;
变量x,y,宽度,高度;
var$images=$(“.img”);
$(函数(){
$images.draggable({
助手:'clone',
});
$images.each(函数(索引、元素){
$(此).数据(“imagesIndex”,索引);
});
$canvas.dropable({
下降:dragDrop,
});
函数dragDrop(e,ui){
x=parseInt(ui.offset.left offsetX)-1;
y=parseInt(ui.offset.top-offsetY-125);
width=ui.helper[0]。宽度;
height=ui.helper[0]。height;
var image=新图像();
var theIndex=ui.draggable.data(“imagesIndex”);
ctx.drawImage($images[theIndex],x,y,width,height);
var tempCanvas=document.createElement('canvas');
var tempCtx=tempCanvas.getContext('2d');
tempCanvas.width=宽度;
高度=高度;
//drawImage(画布,x,y,宽度,高度,0,0,宽度,高度);
var img=新图像();
img.onload=函数(){
ctx.drawImage(图像、x、y、宽度、高度)
};
img.src=tempCanvas.toDataURL();
console.log(img.src);
$(“.img”).dblclick(函数(){
$(this.remove();
});     
}
})
}
更改颜色(参数){
这是我的国家({
颜色:params.target.value
})
}
更改大小(参数){
这是我的国家({
大小:params.target.value
})
}
点击我(){
this.rect=true
警报(this.rect)
}
组件将接收道具(新道具){
this.ctx.strokeStyle=newProps.color;
this.ctx.lineWidth=newProps.size;
}
drawOnCanvas(){
var canvas=document.querySelector(“#board”);
this.ctx=canvas.getContext('2d');
var ctx=this.ctx;
var sketch=document.querySelector(“#dropHere”);
var sketch_style=getComputedStyle(草图);
canvas.width=parseInt(sketch_style.getPropertyValue('width');
canvas.height=parseInt(sketch_style.getPropertyValue('height');
变量鼠标={x:0,y:0};
var last_mouse={x:0,y:0};
/*捕鼠工作*/
canvas.addEventListener('mousemove',函数(e){
last_mouse.x=mouse.x;
last_mouse.y=mouse.y;
mouse.x=e.pageX-this.offsetLeft;
mouse.y=e.pageY-this.offsetTop;
},假);
/*绘画应用程序*/
ctx.lineWidth=this.props.size;
ctx.lineJoin='round';