【问题标题】:How to implement express-ws route如何实现 express-ws 路由
【发布时间】:2018-06-03 00:35:00
【问题描述】:

更新:

我需要正确设置 express-ws:

const express = require('express');
let expressWs = require('express-ws');
expressWs = expressWs(express());
const app = expressWs.app;
const router = express.Router();

const createError = require('http-errors');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
...
const playerHeadingRouter = require('./routes/playerHeading')(router, db);

连同我的路线模块:

module.exports = (router, db) => {
  router.get('/api/player/:id', (req, res, next) => {
    res.end();
  });

  router.ws('/api/player/:id', (ws, req) => {
    ws.on('message', function(msg) {
      const coords = JSON.parse(msg);
      db.any(`UPDATE "user" SET x = ${coords.x} WHERE id = ${req.params.id}`)
      db.any(`UPDATE "user" SET y = ${coords.y} WHERE id = ${req.params.id}`)
      db.any(`UPDATE "user" SET geom = ST_SetSRID(ST_MakePoint(x, y),27700) WHERE id = ${req.params.id}`)
        .then(() => {
          // success;
          console.log('msg', msg);
        })
        .catch(error => {
          // error;
          console.log('error', error);
        });
    });
    // socket
  });
}

现在,当我使用 chrome websockets 客户端时,我可以建立连接到:

ws://localhost:3001/api/player-heading/2

并从我的 express 服务器发送一个用于数据库查询的 msg。

【问题讨论】:

    标签: javascript node.js express websocket


    【解决方案1】:

    如果您托管的是 websocket 端点,您将无法通过 HTTP 访问它。您需要使用 websocket 客户端连接到 ws:// 端点。您可以使用 Chrome 扩展程序 like this one 来执行此操作。

    【讨论】:

    • 谢谢。尝试打开 ws://localhost:3001/echo 给我“未定义”。
    • 您的第二个代码 sn-p 设置为回显客户端发送的任何内容。如果您从客户端发送消息,它会返回吗?
    • 请查看更新。我现在可以建立连接,并且可以通过您提到的浏览器插件向快递服务器发送数据。再次感谢。
    • express-ws 库似乎不再得到积极维护。如果你想要类似的功能,我已经在这里发布了我的解决方案:stackoverflow.com/questions/69773285/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2019-02-09
    • 2019-12-19
    • 2020-11-30
    • 2017-10-07
    • 1970-01-01
    相关资源
    最近更新 更多