socket.io连接不适用于react.js

时间:2019-01-11 08:11:25

标签: reactjs express websocket socket.io nodes

我有一个reactjs项目和node.js项目。现在我需要在我的项目中设置socket.io。但设置后,我得到404错误。我厌倦了使用cross和其他方法,但是仍然遇到相同的404错误。预先感谢

Index.js

const express = require("express");
const port = 3000;
const app = express();
const url = require("url");
var http = require('http').Server(app);
var io = require('socket.io')(http);

const origin = url.parse(`http://${process.env.CII_RESTURL || "localhost"}/`)
.origin;
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");

var path = require("path");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.set("port", port);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.static(__dirname + "./../../"));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
    "Access-Control-Allow-Headers",
    "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With"
);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header('Access-Control-Allow-Credentials', true);
next();
});
// create a GET route
app.get("/express_backend", (req, res) => {
res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" });
});

app.use("/api", router);
var getTags = require("./routes/search");

router.get("/jobSearch", plainSearch.SearchByJob);
// console.log that your server is up and running
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
console.log("Application live on the hostname: " + origin);
});

router.get("/",function(req,res){
res.send("hi")
})
//io.origins(cors());
io.on('connection', function(socket){
console.log("sd");
socket.on('subscribeToTimer', function(msg){
    console.log('message: ' + msg); 
});
});

反应组件

import io from 'socket.io-client';

const socket = io("http://localhost:3000/",{
    path: '/api'
});

    subscribeToTimer(cb) {
    alert("sd");
    socket.on('timer', timestamp => cb(null, timestamp));
    socket.emit('subscribeToTimer', 1000);
} 

在构造函数中调用subscriptionToTimer函数。

1 个答案:

答案 0 :(得分:0)

似乎您没有使用正确的反应生命周期方法来监听套接字。始终使用componentDidMount()来监听套接字或发送API请求。尝试这样的事情。

   subscribeToTimer(cb) {
        alert("sd");
        socket.on('timer', timestamp => cb(null, timestamp));
        socket.emit('subscribeToTimer', 1000);
    }      

     componentDidMount(){
        subscribeToTimer(cb);
    }