【问题标题】:Socket.io and node JS resulting CORS blocked issueSocket.io 和节点 JS 导致 CORS 阻塞问题
【发布时间】:2020-10-28 16:45:01
【问题描述】:

我一直在研究聊天功能。有两种客户端,一种是我的应用程序的前端,另一种是随机的另一个网站。 我知道有很多这样的问题,但我尝试了所有解决方案,但仍然出现以下错误:

CORS 策略已阻止从源“null”访问“https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjoM1w”处的 XMLHttpRequest:“Access-Control-Allow-”的值当请求的凭据模式为“包含”时,响应中的 Origin 标头不能是通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

这是我在自己前端的客户端遇到的错误:

https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjnJUX 404(未找到)

这就是我尝试从客户端连接的方式。

    var socket = io.connect("https://mydomain:443/", {secure: true, port: '443'});

这是我的 server.js 代码

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
// const client = require('socket.io').listen(4000).sockets;
const https = require('https');
const fs = require('fs');

var options = {
  pfx: fs.readFileSync('certificate.pfx'),
  passphrase: 'password'
};

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');
  next();
});

var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*') ;
server.listen(443);

// Bodyparser middleware
app.use(
  bodyParser.urlencoded({
    extended: false
  })
);
app.use(bodyParser.json());

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(
    db,
    { useNewUrlParser: true }, (err, db) => {

      if (err) {
        throw err;
      }
      console.log('MongoDB connected');
      chatSocket(db, client);
    });

// Passport middleware
app.use(passport.initialize());

// Passport config
require("./config/passport")(passport);

// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);

const port = process.env.PORT || 5000;

app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});

app.listen(port, () => console.log(`Server up and running on port ${port} !`));

请帮我解决这个 CORS 和其他问题。我正在使用 Azure 应用服务。这就是为什么我不能使用除 80 和 433 以外的任何其他端口

【问题讨论】:

  • 你在服务器端使用的是哪个socket.io版本?
  • @yueyou 我用的是2.3.0

标签: node.js reactjs socket.io


【解决方案1】:

使用 npm i cors 安装 cors 包

在您的 app.js 文件中, const cors = require('cors')

app.use(cors());

【讨论】:

    【解决方案2】:

    // 像这样使用 CORS- // 你需要使用它作为中间件

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
      });
    

    【讨论】:

      【解决方案3】:

      丹麦人试试这个解决方案,我希望它会奏效

      const client = require("socket.io")(server, {
          handlePreflightRequest: (req, res) => {
              const headers = {
                  "Access-Control-Allow-Headers": "Content-Type, Authorization",
                  "Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
                  "Access-Control-Allow-Credentials": true
              };
              res.writeHead(200, headers);
              res.end();
          }
      });
      
      client.on("connection", () => {
          console.log("Connected!");
      });
      
      server.listen(443);
      

      【讨论】:

        猜你喜欢
        • 2016-07-15
        • 2020-04-18
        • 2016-03-31
        • 2011-03-09
        • 2015-10-11
        • 2016-09-18
        • 1970-01-01
        • 1970-01-01
        • 2019-01-12
        相关资源
        最近更新 更多