Я пытаюсь реализовать приложение чата, используя node.js socket.io и ionic 4, но получаю ошибку политики кросса на стороне клиента
Это мой сервер node.js
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const {Users} = require('./utils/users');
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
var users = new Users();
app.use(express.static(publicPath));
app.use( (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:8100"); //The ionic server
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
io.on('connection', (socket) => {
console.log('New user connected', socket.id);
socket.on('setName', function (data) {
console.log(data);
socket.id = data.name;
});
Вот мой ионный клиент. Я использую плагин ngx-socket-io для клиента socket.io.
import { Component } from "@angular/core";
import { Router } from "@angular/router";
import { NavController } from "@ionic/angular";
import { Socket } from "ngx-socket-io";
@Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"]
})
export class HomePage {
constructor(
private router: Router,
private navCtrl: NavController,
private api: ApiService,
private socket: Socket
) {
this.socket.connect();
this.socket.emit("createMessage", "from ionic ");
}
}
Это моя конфигурация socketIO в модуле приложения
import { SocketIoModule, SocketIoConfig } from "ngx-socket-io";
const config: SocketIoConfig = {
url: "https://appName.herokuapp.com/",
options: {}
};
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
ReactiveFormsModule,
SocketIoModule.forRoot(config),
IonicStorageModule.forRoot(),
IonicModule.forRoot(),
Thisэто ошибка, которую я получаю
Access to XMLHttpRequest at 'https://myappName.herokuapp.com/socket.io/?EIO=3&transport=polling&t=MdcwjRC' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.