【发布时间】:2020-02-24 14:53:20
【问题描述】:
我目前在我的 Angular 应用程序中使用 socket.io 有一个简单的 WebSocket 连接。当我通过 ng serve 运行我的代码时,它工作正常,但是在我部署到我的 Heroku 应用程序后,我收到一个“net::ERR_NAME_NOT_RESOLVED”错误。似乎在设置我的 SocketIoConfig 后,主机名更改为 null,但这仅发生在 Heroku 上。
我的 app.module.ts 中的控制台日志显示在:
- ng serve 正确格式为 'http://localhost:4444'
- Heroku 正确格式为 'https://app-name.herokuapp.com'
但是,在 Heroku 上运行时,我的控制台错误是:
获取https://null/socket.io/?EIO=3&transport=polling&t=N1tbO9M 网络::ERR_NAME_NOT_RESOLVED
为什么主机名变为空?我错过了什么?
app.enter code heremodule.ts 文件:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ChartsModule } from 'ng2-charts';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FlexLayoutModule } from '@angular/flex-layout';
import { PlayerStatsComponent } from './player-stats/player-stats.component';
import { playerName, filterByRole, orderHeroBy, greaterThan10m, replace } from './custom.pipe';
import { HomePageComponent } from './home-page/home-page.component';
import { WinrateComponent } from './winrate/winrate.component';
import { FormsModule } from '@angular/forms';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
let port = ( window.location.hostname === 'localhost' ) ? ':8080' : '';
let url = `${window.location.protocol}//${window.location.hostname}${port}`;
const config: SocketIoConfig = { url: url, options: {} };
console.log( config );
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
PlayerStatsComponent,
playerName,
filterByRole,
greaterThan10m,
orderHeroBy,
HomePageComponent,
WinrateComponent,
replace
],
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
ChartsModule,
FlexLayoutModule,
FormsModule,
SocketIoModule.forRoot(config)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
server.js 文件
//Install express server
const express = require( 'express' );
const path = require( 'path' );
const http = require('http');
const https = require('https');
// webserver
const app = express();
app.use( express.static( __dirname + '/dist/statwatchII' ) );
app.get( '/*', function( req, res ) {
res.sendFile( path.join( __dirname+'/dist/statwatchII/index.html' ) );
});
// socketserver
const port = process.env.PORT || 8080;
const server = http.Server(app);
const io = require( 'socket.io' )( server );
io.on( "connection", ws => {
console.log( 'connected' );
} )
server.listen( port, () => { console.log( `listening on port: ${port}`) } );
【问题讨论】: