我正在开发一个使用www.example.com进行实时通信的Node.js应用程序Socket.io。我正在Microsoft Azure上部署此应用程序,在配置WebSocket连接的路径和CORS设置时遇到问题。具体来说,我想为应用程序的各个部分设置不同的路径和CORS源。下面是我的代码的简化版本:
服务器配置:
import { createServer } from "http";
import express from "express";
import { Server } from "socket.io";
const app = express();
const server = createServer(app);
const PORT = process.env.PORT || 8000;
// Setting up Socket.io for "spareparty"
let ioSpareParty = gameRoutes.setIoSpare(server);
useAzureSocketIO(ioSpareParty, {
hub: "spare_hub",
connectionString: process.argv[2] || process.env.WebPubSubConnectionString,
});
ioSpareParty.on("connection", spareParity);
// More code here...
const start = async () => {
try {
await connectDB(databaseUrl);
server.listen(PORT, console.log("Server running at " + PORT));
} catch (error) {
console.log(error);
}
};
start();
Socket.io配置:
// Inside "_iospareparity.js"
const setIoSpare = (server) => {
_ioSpareParty = new Server(server, {
path: "/api/v1/games/spareparty", // What should be the path here ?
cors: {
origin: "http://localhost:5173", // What should be the origin here ?
methods: ["GET", "POST"],
allowedHeaders: [
"Origin",
"X-Requested-With",
"Content-Type",
"Accept",
"Authorization",
],
credentials: true,
optionSuccessStatus: 200,
},
});
return _ioSpareParty;
};
我想为应用程序的“spareparty”、“fastparty”和“easyparty”部分配置WebSocket路径和CORS设置。确保每个零件都有自己独特的路径和CORS原点。我应该遵循哪些步骤来在Microsoft Azure上实现此配置?我是否需要在Azure的配置中调整任何特定设置,或者我应该在代码中进行更改?任何指导或示例都将非常感谢。
Package.json文件:
{
"name": "hello",
"version": "1.0.0",
"main": "app.js",
"type": "module",
"scripts": {
"start": "node app.js",
"server": "nodemon server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^3.0.1"
},
"dependencies": {
"@azure/web-pubsub-socket.io": "^1.0.0-beta.6",
"axios": "^1.5.0",
"bcrypt": "^5.1.0",
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.1",
"moment-timezone": "^0.5.43",
"mongodb": "^5.7.0",
"mongoose": "^7.4.3",
"node-cron": "^3.0.2",
"node-schedule": "^2.1.1",
"otp-generator": "^4.0.1",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2",
"uuid": "^9.0.0"
},
"keywords": [],
"description": ""
}
1条答案
按热度按时间gv8xihay1#
Azure上的Node.js应用程序应针对应用程序的不同部分具有不同的WebSocket路径和CORS设置,如下所示。
setIoSpare
函数以接受路径和原点作为参数(“spareparty”、“fastparty”和“easyparty”)。每个Socket.io示例将使用其指定的路径和源,它们可以独立通信。