在浏览器控制台中..响应中“Access-Control-Allow-Credentials”标头的值为“”,必须为“真”
Posted
技术标签:
【中文标题】在浏览器控制台中..响应中“Access-Control-Allow-Credentials”标头的值为“”,必须为“真”【英文标题】:In Browser console ..The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' 【发布时间】: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);
【问题讨论】:
下面的代码对你有用吗? 【参考方案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);
【讨论】:
以上是关于在浏览器控制台中..响应中“Access-Control-Allow-Credentials”标头的值为“”,必须为“真”的主要内容,如果未能解决你的问题,请参考以下文章