简体   繁体   English

Socket.io 和节点 JS 导致 CORS 阻塞问题

[英]Socket.io and node JS resulting CORS blocked issue

I've been working on chat functionality.我一直在研究聊天功能。 There are two kinds of clients, One is the frontend of my application and the second is random another website.有两种客户端,一种是我的应用程序的前端,另一种是随机的另一个网站。 I know there are plenty of issues like this but I tried all of the solution but I'm still getting following error:我知道有很多这样的问题,但我尝试了所有解决方案,但仍然出现以下错误:

Access to XMLHttpRequest at 'https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjoM1w' from origin 'null' 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'. Access to XMLHttpRequest at 'https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjoM1w' from origin 'null' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header当请求的凭据模式为“包含”时,响应中的内容不能是通配符“*”。 The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

and this the error I'm getting on client-side of my own front end:这是我在自己前端的客户端遇到的错误:

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

This is how I'm trying to connect from client-side.这就是我尝试从客户端连接的方式。

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

and this is my server.js code这是我的 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} !`));

Please help me resolve this CORS and other issues.请帮我解决这个 CORS 和其他问题。 I am using the Azure app service.我正在使用 Azure 应用服务。 That's why I can't use any other port than 80 and 433这就是为什么我不能使用除 80 和 433 以外的任何其他端口

// use CORS like that- // you need to use it as middle ware // 像这样使用 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();
  });

Danish try this solution, I hope it will work丹麦人尝试这个解决方案,我希望它会奏效

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);

Install cors package using npm i cors使用 npm i cors 安装 cors package

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

app.use(cors()); app.use(cors());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM