【发布时间】:2020-05-03 06:13:25
【问题描述】:
我正在尝试将 socket.io 连接与 firebase 托管/功能一起使用,但我遇到了一些问题。它从 CORS 问题开始(我确定这仍然是问题),但现在我完全迷失了,下面是我的 firebase.json、index.js(firebase 函数文件),甚至是 angular 客户端文件初始化与服务器的连接。
firebase.json
{
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"headers": [
{
"source" : "**",
"headers" : [ {
"key" : "Access-Control-Allow-Headers",
"value" : "Origin"
} ]
},
{
"source" : "**",
"headers" : [ {
"key" : "Access-Control-Allow-Origin",
"value" : "http://localhost:4200"
} ]
}
],
"rewrites": [
{
"source": "**",
"function": "app"
}
]
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
],
"source": "functions"
}
}
index.js
const functions = require('firebase-functions');
const express = require('express');
var app = express();
const http = require('http').Server(express);
const socketio = require('socket.io')(http);
const cors = require('cors');
app.use(cors({credentials: true, origin: '*:*'}));
app.get('/tester', (request, response) => {
//response.header('Access-Control-Allow-Origin', '*');
response.send('Hello!');
socketio.on('connection', socket => {
connections.push(socket);
console.log('New client connected ('+connections.length+' connections).');
//console.log(socket);
socket.emit('port', 'LIVE SHIT');
});
})
exports.app = functions.https.onRequest(app)
app.component.ts(用于连接的客户端组件)
import { Component } from '@angular/core';
import io from 'socket.io-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'multi-client';
port: number = 0;
socket: any;
width: number = 100;
updateVal: number = 5;
constructor()
{
this.socket = io('http://localhost:5000/tester');
this.socket.on('port', port => {
this.port = port;
})
}
updateWidth(val)
{
this.width += val;
}
}
我在 stackoverflow 和其他各种网站上查看了一些帖子,这些帖子有类似的问题,但似乎没有任何效果。我确定我做错了,但我迷失了实现这一目标所缺少的东西。请帮忙!
【问题讨论】:
标签: node.js firebase express google-cloud-functions firebase-hosting