Node.js解析路由的最小功能 [英] Node.js minimal function for parsing route
问题描述
我有一个正在运行的Node.js / Express应用,它接收到的路由如下:
I have a Node.js / Express app working, that receives routes like so:
app.get('/resource/:res', someFunction);
app.get('/foo/bar/:id', someOtherFunction);
这很棒,可以正常工作。
This is great and works fine.
我也在使用Socket.IO,并且希望一些服务器调用使用websocket而不是传统的RESTful调用。但是,我想使其非常干净并几乎使用相同的语法,最好:
I am also using Socket.IO, and want to have some server calls use websockets instead of traditional RESTful calls. However, I want to make it very clean and almost use the same syntax, preferrably:
app.sio.get('/resource/:res', someFunction);
这将为Socket.IO提供一个综合的 REST接口,从程序员的角度来看,他没有做任何不同的事情。只需从客户端标记 websockets:true
。
This will give a synthetic 'REST' interface to Socket.IO, where, from the programmer's perspective, he isn't doing anything different. Just flagging websockets: true
from the client.
我可以处理所有详细信息,例如自定义方式传递请求动词并解析它们等等,我对此没有问题。我正在寻找的唯一的东西是一些函数,可以像Express一样解析路由,并正确地路由它们。例如,
I can deal with all the details, such as a custom way to pass in the request verbs and parse them and so and so, I don't have a problem with this. The only thing I am looking for is some function that can parse routes like express does, and route them properly. For example,
// I don't know how to read the ':bar',
'foo/:bar'
// Or handle all complex routings, such as
'foo/:bar/and/:so/on'
我可以深入挖掘并自己编写代码,或者尝试阅读所有express的源代码并找到他们在哪里做,但我确保它本身存在。只是不知道在哪里找到它。
I could dig in real deep and try to code this myself, or try to read through all of express' source code and find where they do it, but I am sure it exists by itself. Just don't know where to find it.
robertklep提供了一个很好的答案,这完全解决了这个问题为了我。我将其调整为完整的解决方案,并在下面的答案中发布。
robertklep provided a great answer which totally solved this for me. I adapted it into a full solution, which I posted in an answer below.
推荐答案
您可以使用Express路由器类来做繁重的工作:
You can use the Express router class to do the heavy lifting:
var io = require('socket.io').listen(...);
var express = require('express');
var sioRouter = new express.Router();
sioRouter.get('/foo/:bar', function(socket, params) {
socket.emit('response', 'hello from /foo/' + params.bar);
});
io.sockets.on('connection', function(socket) {
socket.on('GET', function(url) {
// see if sioRouter has a route for this url:
var route = sioRouter.match('GET', url);
// if so, call its (first) callback (the route handler):
if (route && route.callbacks.length) {
route.callbacks[0](socket, route.params);
}
});
});
// client-side
var socket = io.connect();
socket.emit('GET', '/foo/helloworld');
您显然可以随请求传递额外的数据,并将其传递给路由处理程序(以及例如一个额外的参数。)
You can obviously pass in extra data with the request and pass that to your route handlers as well (as an extra parameter for example).
这篇关于Node.js解析路由的最小功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!