更新:
我需要正确设置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
并从我的快速服务器发送一个在数据库查询中使用的消息。
答案 0 :(得分:0)
如果您正在托管websocket端点,您将无法通过HTTP访问它。您需要使用websocket客户端连接到ws://端点。您可以使用Chrome扩展程序like this one来执行此操作。