代码之家  ›  专栏  ›  技术社区  ›  Shashwat Gupta

在浏览器控制台中。。响应中“Access Control Allow Credentials”标头的值为“”,必须为“true”

  •  0
  • Shashwat Gupta  · 技术社区  · 3 年前

    在“”访问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);
      }
    
    
    }
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   Devesh Goyal    3 年前

    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
  •  0
  •   Taylor Rahul    3 年前

    在后端/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);