【发布时间】: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