【问题标题】:CORS Error in socket.io when using NodeJS / Express and HTTPS使用 NodeJS / Express 和 HTTPS 时 socket.io 中出现 CORS 错误
【发布时间】:2019-11-09 19:58:05
【问题描述】:

我使用下面的代码能够从我的应用程序的不同部分访问 socket.io。在开发服务器上一切正常,但是一旦我在 HTTPS 服务器上进行生产尝试,它就会失败并出现以下错误。

从源“http://127.0.0.1:9999”访问“https://nodejs.demo.net/socket.io/?EIO=3&transport=polling&t=MkQBnlU”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”的值' 当请求的凭证模式为 'include' 时,响应中的标头不能是通配符 '*'。 XMLHttpRequest发起的请求的凭证模式由withCredentials属性控制

在我的 app.js 文件中,我这样启动它

const express = require('express');
const app = express();
const https = require('https');
const io = require('sio').init(https);

var options = {
  key: fs.readFileSync('./cert/nodejs.demo.net.key'),
  cert: fs.readFileSync('./cert/ServerCertificate.cer')
};

https.createServer(options, app).listen(443,()=>{
  console.log("listening secure via SSL on 443")
})

这里是sio文件的内容

const socketio = require('socket.io');
let io;

module.exports = {
   init: function(server) {
        if (io) {
            throw new Error("socket.io already initialized");
        }
        // initalize socket.io to this server
        io = socketio(server);

        // put other socket.io initialization code here

        return io;
   }
   get: function() {
        if (!io) {
             throw new Error("socket.io has not yet been initialized");
        }
        return io;
   }
}

那么我在哪里以及如何修复 cor 的错误?

【问题讨论】:

    标签: node.js socket.io


    【解决方案1】:

    你的服务器应该允许 CORS 请求,试试CORS module:

    // Enable All CORS Requests
    const cors = require('cors')
    
    app.use(cors())
    

    使用您的代码:

    const express = require('express');
    const app = express();
    const https = require('https');
    const io = require('sio').init(https);
    const cors = require('cors');
    
    app.use(cors());
    
    var options = {
      key: fs.readFileSync('./cert/nodejs.demo.net.key'),
      cert: fs.readFileSync('./cert/ServerCertificate.cer')
    };
    
    https.createServer(options, app).listen(443,()=>{
      console.log("listening secure via SSL on 443")
    })
    

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 2021-01-21
      • 2017-11-30
      • 2019-02-02
      • 2021-03-07
      • 2023-03-15
      • 2015-06-24
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多