node.js - (Nodejs + Angular 6 + socket.io) 中的 CORS 问题
问题描述
当我们尝试连接到服务器时,我们使用 socket.io 客户端在 Angular 6 中面临 CORS 问题。
我们在浏览器控制台中遇到的错误。
Access to XMLHttpRequest at 'http://********.com/socket.io/?EIO=3&transport=polling&t=N3jTiAZ' from origin 'http://localhost:4200' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
这是服务器代码
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
const conn = app.listen("3000")
const io = require('socket.io').listen(conn);
io.origins('*:*')
var connectioncheck = io.of('/check-connection');
connectioncheck.on('connection', function (socket) {
console.log('user connected');
});
这是使用简单 html 和 js 的前端代码
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
var socket = io.connect('http://********.com/check-connection');
socket.emit('connection', "hello",function(db){
console.log(db);
console.log("data from callback");
});
解决方案
根据您在上面给出的评论,我认为您应该以这样的方式使用 NPM CORS
let allowedOrigins = ["http://ServerA:3000", "http://ServerB:3000"]
let origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header("Access-Control-Allow-Origin", origin); // restrict it to the required domain
}
推荐阅读
- sql-server - 登录/用户帐户只有在设置为 sysadmin 服务器角色时才能执行存储过程
- c# - WebControl Label 像 Span 一样呈现
- excel - Excel VBA 在工作表上生成 #N/A 错误
- python - 我想从 excel 表中复制一个值并将其粘贴到网页的搜索框中。任何帮助表示赞赏
- flutter - 我怎样才能在颤动中获得http响应
- python - Django“调度前”混合
- typescript - 如何从记录类型创建有区别的联合类型?
- arrays - Go 代码报告更新切片的底层数组不正确?
- python - 将 pandas DataFrame 转换为嵌套字典
- csv - 我们如何加入多个文件,其中每个文件的第一列相同但第二列的结果不同?