Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NQFEnVV' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是nodejs服务器:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 5000;
app.set(port, process.env.PORT);
app.use(express.static('./client/'));
io.on('connection', socket => {
socket.emit('connection', 'data from server!');
});
http.listen(port, () => {
console.log('App listening on port ' + port);
});
这就是我在 Angular 客户端上实现 socket.io 的方式:app.module.ts:
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const hostname = window.location.hostname;
const url = (hostname === 'localhost') ? `${window.location.protocol}//${hostname}:5000` : undefined;
const config: SocketIoConfig = { url, options: {} };
@NgModule({
declarations: [...],
imports: [
...
SocketIoModule.forRoot(config)
使用套接字 io 的类:
constructor(private socket: Socket) { }
this.socket.on('connection', (data) => {
console.log('Working ' + data);
});
我尝试修复服务器端标头的 CORS 错误,例如:
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
或
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
但它仍然显示相同的错误。我当然使用命令
ng serve
来运行我的应用程序(在端口 4200 上运行),并且它在 3 个月前运行良好。 (与 ngserve 以及 ng build prod 一起使用)。
packaje.json
文件上的 socket.io-client 版本。如果低于 3.1.2 您可以尝试通过以下方式升级
npm install [email protected] --save
您也可以再次验证服务器端,看看这个
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:4200']
}
});
将 http://localhost:4200
替换为 Angular 应用程序上当前的环境
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"]
}
});
您可以添加或删除方法也尝试添加这个
var cors = require('cors');
app.use(cors());
那个
cors: { origins: ['http://localhost:4200']}
对我不起作用,所以我在 Angular 项目中建立了一个代理文件来解决 CORS。在 src/proxy.config.json 文件中添加文件
{
"/api": { // this attaches /api/ in api url
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
},
"/": { // use this as second entry
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}
在 angular.json 中,添加以下内容;
"serve": {
"options": {
"browserTarget": "move-safe:build",
"proxyConfig": "src/proxy.config.json"
},
并重新构建角度应用程序