我在heroku端有一个node.js服务器,这是在localhost上工作但是当我提交到heroku时,应用程序崩溃了。
'use strict';
const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const io = socketIO(server);
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
});
var app = express();
app.set('port', (process.env.PORT || 5000));
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'))
app.post('/phpcallback', function(req, res) {
var content = req.body;
console.log('message received from php: ' + content.msg);
//to-do: forward the message to the connected nodes.
res.end(content.msg);
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
});
应用程序需要侦听来自我的PHP服务器的POST请求,然后在js客户端向用户发出,代码在localhost上运行良好,但是当我提交并推送到heroku应用程序崩溃时。 有谁知道这是什么问题?我是node.js和socket.io
的新手答案 0 :(得分:0)
尝试这样(改进的语法和一般用法)
var express = require('express');
var io = require('socket.io');
var path = require('path');
var PORT = process.env.PORT || 3000;
var INDEX = path.join(__dirname, 'index.html');
// Express & Middleware
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// SocketIO
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){
console.log('[socket]','client connected');
socket.on('disconnect', () => console.log('[socket]','client disconnected'));
});
server.listen(PORT,function(){console.log("[SERVER] listening @ port:",PORT);});
//GET Routes
app.use(express.static(__dirname + '/public'))
app.get('/',function(req,res){res.sendFile(INDEX);});
//POST Routes
app.post('/phpcallback', function(req, res) {
var content = req.body;
if(content.msg){
console.log('message received from php: ' + content.msg); //
/*to-do: forward the message to the connected nodes.*/
//io.sockets.on('forward',content.msg); //forward to ALL connected socket.io clients (requires client-side event)
res.send(content.msg); //forward response with content.msg to the original request (only) of this route.
}else{console.log('[/phpcallback] : missing message (content.msg)');}
});
如果您要将消息转发给所有连接的客户端socket.io:
,我看到了您的to-do
io.sockets.emit('your_event','your_message');
这可能会派上用场:SocketIO Emit CheatSheet