首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >(Nodejs + Angular 6+ socket.io)中的CORS问题

(Nodejs + Angular 6+ socket.io)中的CORS问题
EN

Stack Overflow用户
提问于 2020-03-18 19:57:25
回答 1查看 911关注 0票数 0

当我们试图连接到服务器时,我们在Angular 6中遇到了使用socket.io客户端的CORS问题。

我们在浏览器的控制台中得到的错误。

代码语言:javascript
代码运行次数:0
运行
复制
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.

以下是服务器代码

代码语言:javascript
代码运行次数:0
运行
复制
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的前端代码

代码语言:javascript
代码运行次数:0
运行
复制
   <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");
    });
EN

回答 1

Stack Overflow用户

发布于 2020-03-18 20:13:20

根据您上面的评论,我认为您应该以类似this的方式使用NPM CORS。

代码语言:javascript
代码运行次数:0
运行
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60739097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档