在“”访问XMLHttpRequesthttp://localhost:3000/socket.io/?EIO=3&传输=轮询和;t=NQb0Bxp“来自原点”http://localhost:8100“已被CORS策略阻止:响应中“Access Control Allow Credentials”标头的值为“”,当请求的凭据模式为“include”时,该值必须为“true”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。
在Node.js(后端)中
var express = require('express');
var app = express();
const cors = require('cors');
app.use(cors());
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var server = require('http').createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:8100",
methods: ["GET", "POST"],
}
});
io.on('connection',function(socket){
console.log("A user connected");
// socket.emit('test event','my connection');
socket.on('test event',(data)=>{
console.log(data);
socket.emit('test event','my connection');
})
})
// console.log(app)
server.listen(3000,()=>{
console.log("socket io server is listening on port 3000");
});
在角度
websocker.service.ts
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
socket:any;
readonly url = "ws://localhost:3000";
constructor() {
console.log(io,"io")
this.socket = io.connect(this.url,{});
}
listen(eventName:string){
return new Observable((subscriber)=>{
this.socket.on(eventName , (data)=>{
subscriber.next(data);
});
})
}
emit(eventName:string,data:any){
this.socket.emit(eventName,data);
}
}