Hello! I am trying to integrate server events into an existing application, but I am having issues connecting to the event stream.
I was successfully able to create and subscribe to the event stream of a fresh test project, simply by adding the ServerEventsFeature plugin, and accessing it from a Vue front end project. I added the plugin the same way to the existing application, and tried to connect from both the application’s front end and the test Vue project, but I receive this CORS error:
Access to resource at 'http://localhost:8585/event-stream?channel=test&t=1585230470861' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
When I try to access the URL directly, I receive a 404 error. Here is my apphost.cs file:
public class AppHost : AppHostHttpListenerPoolBase
{
public ILog log = LogManager.GetLogger(typeof(AppHost));
public AppHost()
: base("Cognos Loading Utility", typeof(CustomerService).Assembly) { }
public override void Configure(Container container)
{
LogManager.LogFactory = new NLogFactory();
log.InfoFormat("Loading Configuration");
var appSettings = new AppSettings();
var fc = appSettings.Get<FolderConfiguration>("FolderConfiguration");
container.Register<IFolderConfiguration>(fc);
log.InfoFormat("Loading Configuration Folder: Input Folder: ({0}) Output Folder: ({1})", fc.InputFolder, fc.OutputFolder);
Plugins.Add(new OpenApiFeature());
log.InfoFormat("Loading OpenAPI aka Swagger");
var connString = ConfigUtils.GetConnectionString("Cognos");
OrmLiteConnectionFactory dbFactory = new OrmLiteConnectionFactory(connString, new SqlServer2016OrmLiteDialectProvider());
container.Register<IDbConnectionFactory>(dbFactory);
log.InfoFormat("Connection string:{0}", connString);
log.InfoFormat("Configuration Loaded");
log.InfoFormat("Migrate Database");
var dbMigration = new DatabaseMigration(dbFactory);
dbMigration.MigrateDatabase();
Plugins.Add(new ServerEventsFeature());
Plugins.Add(new CorsFeature(
allowOriginWhitelist: ConfigurationManager.AppSettings["CorsOriginWhitelist"].Split(','),
allowedMethods: "GET,POST,PUT,OPTIONS",
allowCredentials: true,
allowedHeaders: "Authorization, Content-Type"
));
}
And here is the front-end code I’m using:
this.sseStream = new EventSource('http://localhost:8585/event-stream?channel=test&t=' + new Date().getTime())
this.sseStream.addEventListener('connect', event => {
console.log('Connect event fired.')
console.log(event.data)
}, false)
this.sseStream.addEventListener('open', event => {
console.log('Open event fired.')
console.log(event.data)
}, false)
this.sseStream.addEventListener('message', event => {
console.log('Message event fired.')
console.log(event.data)
}, false)
Any help would be very appreciated, thanks!