本文介绍了无法打印由socket.io和express-nodejs发出的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在socket.io中遇到问题.我的代码未在特定路线上发出.在"/"上,此路由工作正常,但是一旦单击提交"按钮,将路由更改为"/process_post",则无法通过sock.io捕获发出的值.请帮助我解决问题.在这里,我粘贴我的代码.server.js

I am facing a problem in socket.io. My code is not emitting value on particular route. On '/' this route it is working fine, but once I click submit button, route changes to '/process_post' there I am not able to catch the emitted values by sock.io. please help me to solve the problem. Here I am pasting my code.server.js

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');

var bodyParser = require('body-parser');

app.use(express.static('public'));

var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})

app.post('/process_post', urlencodedParser, function (req, res) {

   // Prepare output in JSON format
   response = {
       first_name:req.body.first_name,
       last_name:req.body.last_name
   };
   console.log(response);
    io.of('/process_post').on('connection', function(socket){
        socket.emit('news', { hello: 'world' });
    console.log('a user connected');
  });

res.end(JSON.stringify(response));
})

server.listen(3000, function(){
  console.log('listening on *:3000');
});

还有我的index.html文件

And my index.html file

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<form action="/process_post" method="POST">
First Name: <input type="text" name="first_name">  <br>

Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
<script>
  var socket = io.connect('http://localhost:3000');
  socket.on('news', function (data) {
        console.log(data);
  });
</script>
</body>
</html>

推荐答案

看看他们的文档: http://socket.io/docs/#restricting-yourself-to-a-命名空间

在前端实例化套接字时,它需要连接到您设置的名称空间.

When instantiating your socket on the front end it needs to connect to the namespace you set.

var socket = io.connect('http://localhost:3000/process_post');

我还将在后端的路由之外删除套接字声明,否则事件处理程序将不会被附加,因为直到路由被点击(在最初的套接字连接之后)才调用该部分代码.

Also I would remove the socket declaration outside your route on the backend, otherwise the event handlers would not be attached due to that part of code not being called until the route is hit which would be after the initial socket connection.

这篇关于无法打印由socket.io和express-nodejs发出的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 04:24