我正在尝试使用node.js socket.io和ionic 4实现聊天应用程序,但是在客户端出现Cros策略错误
这是我的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;
});
这是我的离子客户端,我正在为Socket.io客户端使用ngx-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(),
这是我得到的错误
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.
答案 0 :(得分:1)
尝试以下
https://example.com/hub/user-redirect/proxy/39000 -> example.com/user/ytl/proxy/39000
如果它不起作用,请尝试使用CORS软件包,
要安装
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8100');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
用于:
npm install cors --save