【问题标题】:In Browser console ..The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true'在浏览器控制台中..响应中“Access-Control-Allow-Credentials”标头的值为“”,必须为“真”
【发布时间】:2021-04-04 15:40:36
【问题描述】:

CORS 策略已阻止从源“http://localhost:8100”访问“http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NQb0Bxp”处的 XMLHttpRequest:值响应中的“Access-Control-Allow-Credentials”标头为“”,当请求的凭据模式为“包含”时,该标头必须为“真”。 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);
  }


}

【问题讨论】:

  • 下面的代码对你有用吗?

标签: node.js angular ionic-framework socket.io


【解决方案1】:

Socket.io (3.x) 的迁移文档很有帮助。

const io = require("socket.io")(httpServer, {
  cors: {
    origin: "https://example.com",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }
});

【讨论】:

    【解决方案2】:

    在您的后端/nodejs 代码中

    代替

    const io = require("socket.io")(server, {
    cors: {
        origin: "http://localhost:8100",
        methods: ["GET", "POST"],
    }
    });
    

    请使用以下代码

    app.use(function(req,res,next){  
        res.header('Access-Control-Allow-Origin','* or secific')  
        next(); 
    })
    
    const io = require("socket.io")(server);
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2019-02-08
      • 2017-10-02
      • 2018-01-13
      • 2015-04-14
      • 2021-04-17
      • 2021-03-12
      • 2022-11-28
      相关资源
      最近更新 更多