我正在用 Vue 实现一个网络应用程序。在我的应用程序中,我使用 Pusher 来实现实时多用户通信。
在本地,该应用程序在“ http://localhost:8080 ”上运行,我在“ http://localhost:5000 ”上设置了一个 node.js 服务器,该服务器管理推送器共享频道上的用户订阅和它们之间的事件共享。该应用程序运行良好。现在我想将它部署在托管服务器上以使其在 Internet 上运行。
我的问题与需要使用两个不同的端口有关。特别是我不知道如何组织我的“server.js”文件来做到这一点(或者像 Heroku 这样的平台是否可以支持使用两个端口)。下面我发布了我的实际“server.js”文件。我希望你可以帮助我。
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()
const Pusher = require('pusher')
const crypto = require('crypto')
const cors = require('cors')
//initialize Pusher with your appId, key and secret
const pusher = new Pusher({
appId: '***',
key: '******',
secret: '*****',
cluster: 'eu',
useTLS: true
})
// Body parser middleware
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false}))
app.use(cors())
// The code below helps to fix any potential CORS issue.
app.use((req, res, next) => {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*')
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', false)
// Pass to next layer of middleware
next()
})
// Index API route for the Express app
app.get('/', (req, res) => {
res.send('Welcome')
})
// API route used by Pusher as a way of authenticating users
app.post('/pusher/auth', (req, res) => {
let socketId = req.body.socket_id
let channel = req.body.channel_name
// Generate a random string and use as presence channel user_id
let presenceData = {
user_id: crypto.randomBytes(16).toString('hex')
}
let auth = pusher.authenticate(socketId, channel, presenceData)
res.send(auth)
})
// Set port to be used by Node.js
app.set('port', (5000))
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'))
})
您使用的是 Vue,因此在开发中,前端由 Webpack 的 devServer 在端口 8080 上本地提供服务。您还在开发中运行一个节点服务器,它模拟生产服务器的 API 部分。
在实际生产中,不需要2台服务器或2个端口。在生产中,您的前端不需要专用服务器。这只是为了快速方便的开发。让节点生产服务器也为前端服务。像这样的事情取决于您的服务器结构:
// Static assets
app.use(express.static(path.join(__dirname, 'dist')));
Heroku 不支持多个端口,您也不需要它们。从一个域同时服务后端和前端是可能的(也是正常的)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句