我正在使用Express和Socket.io,但我无法弄清楚如何在Express路线中使用SocKet.io。
我最终在“app.js”
中这样做了...
...
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var server = http.createServer(app);
var io = require("socket.io").listen(server);
app.get('/', routes.index);
app.get('/users', user.list);
app.post('/cmp', function(request, response) {
var client = new pg.Client("pg://user:pass@127.0.0.1/db_name");
client.connect(function(err) {
// Get the product_id and bid
var product_id = request.body.product_id;
var bid = request.body.bid.split('b')[1];
// If not get the connection
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('select 1 from product_bid where product_id = $1 and number_bid = $2', [product_id, bid], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (result.rowCount == 1) {
// do not insert
} else {
// insert
// Insert to the DB
client.query('insert into product_bid (product_id, number_bid) values ($1, $2)', [product_id, bid], function(err, result) {
if(err) {
return console.error('error running query', err);
}
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
client.end();
});
}
});
});
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
// ---------------
io.on('connection', function(socket){
console.log("alguem se ligou!");
socket.emit('event_from_server', {message: 'conectou-se ao servidor'});
});
如何将路径定义为“/ cmp”,并将var“io”传递到内部?
app.post('/cmp', routes.cmp);
所以在“/routes/cmp.js”中我可以这样做:
exports.cmp = function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
};
一些线索?
答案 0 :(得分:47)
高阶函数怎么样?
exports.cmp = function(io) {
return function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
}
};
然后
app.post('/cmp', routes.cmp(io));
作为另一种选择,我有时会按以下格式格式化我的路线:
var routes = require('./routes/routes');
routes(app, io);
然后将routes
定义为
module.exports = function(app, io) {
app.post('/cmp', function(req, res){
var product_id = req.body.product_id;
var bid = req.body.bid.split('b')[1];
io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
response.json(200, {message: "Message received!"});
})
};
答案 1 :(得分:4)
您可以在路由之前使用简单的中间件,然后在res对象中使用
app.use((req, res, next) => {
res.io = io
next()
})