【问题标题】:How set socket.io CORS for heroku?如何为heroku设置socket.io CORS?
【发布时间】:2021-08-07 23:51:43
【问题描述】:

如果我将 socket.io 与 Express 一起使用,如何为 heroku 设置 CORS?我的应用程序可以在 localhost 上运行,但是当我在 Heroku 上部署时,它不能在手机和 Chrome 上运行。当我在 chrome 上检查 console.log 时,我得到了这个错误。

A`ccess to XMLHttpRequest at 'https://fart-game.herokuapp.com/socket.io/?EIO=4&transport=polling&t=Nc0YKct' from origin 'http://fart-game.herokuapp.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value 'https://fart-game.herokuapp.com/'.`

我的 index.js 看起来像这样

const express = require('express');
const path = require('path');
const http = require('http');
const socketio = require('socket.io');

const { addUser, getUser, getUsersInRoom, removeUser } = require('./users');
const { rollFunction, 
        sumNumbers
    } = require('./game')

var cors = require('cors');

const app = express();
app.use(cors())

const buildPath = path.join(__dirname, '..', 'build');
 app.use(express.static(buildPath));

const server = http.createServer(app);

const io = socketio(server, {
    cors: {
        origin: `https://fart-game.herokuapp.com/`,
        methods: ["GET", "POST"],
        credentials: true
      }
});

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

const router = require('./router');
const { get } = require('./router');
const { isFunction } = require('util');

app.use(router)

server.listen(PORT, () => {
    console.log(`Server is runing on port ${PORT}`);
});

依赖关系

"cors": "^2.8.5",
 "express": "^4.17.1",
 "socket.io": "^4.0.1"

【问题讨论】:

    标签: node.js express heroku socket.io


    【解决方案1】:

    我在错误中注意到了这部分

     from origin 'http://fart-game.herokuapp.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value 'https://fart-game.herokuapp.com/'.`
    

    你接受来自https://fart-game.herokuapp.com/的跨域请求,但实际上是从http://fart-game.herokuapp.com发送请求,所以它不起作用。

    我认为这应该可行:

    const io = socketio(server, {
        cors: {
            origin: `http://fart-game.herokuapp.com`, // I copied the origin in the error message and pasted here
            methods: ["GET", "POST"],
            credentials: true
          }
    });
    

    【讨论】:

    • 是的,它现在可以工作了.. 下次需要更多地关注 HTTP 和 HTTPS :)
    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 2012-05-01
    • 2020-02-21
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多