【发布时间】:2021-03-29 12:44:59
【问题描述】:
我创建了一个应用程序,它使用 Angular 作为前端,使用 node.js 作为后端。我在 Firebase Hosting 上托管前端,在 Heroku 上托管服务器(因为我读到 Firebase Functions 不支持 socket.io)。
在我的socket.service.ts 文件中,我使用this.socket = io(environment.socket_url); 连接到套接字(socket_url 是http://localhost:3000/ 用于开发环境,https://PROJECT_NAME_HERE.herokuapp.com:3000 用于生产环境)。
我的server.ts 文件中的套接字连接是:
const port = process.env.PORT || 3000;
const server = new http.Server(app);
const io = new Server(server, {
cors: {
origin: socketUrl,
methods: ["GET", "POST"]
}
});
其中 socketUrl 在开发中是 http://localhost:4200,在生产中是 https://PROJECT_NAME_HERE.web.app/。
此设置适用于开发,但不适用于生产。我该如何让它发挥作用?
编辑:
这是我得到的错误:
Access to XMLHttpRequest at 'https://PROJECT_NAME_HERE.herokuapp.com/socket.io/?EIO=4&transport=polling&t=NPu1t39' from origin 'https://PROJECT_NAME_HERE.web.app' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://PROJECT_NAME_HERE.web.app/' that is not equal to the supplied origin.
我也在用app.use(cors({origin: true}));
【问题讨论】:
-
"但在生产中不起作用" === 需要调试细节。 “不起作用”是不可重现或解决的。
-
@RandyCasburn 感谢您指出这一点。我用我得到的错误编辑了我的问题。
标签: node.js angular firebase heroku socket.io