Node、ReactJS、Express 组合中的跨源请求被阻止

git*_*itu 4 node.js cors express reactjs

我厌倦了所有浏览器中的以下问题

\n\n
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://vid-129002.hls.chinanetcenter.broadcastapp.agoraio.cn/live/pub421490684319281/playlist.m3u8. (Reason: CORS header \xe2\x80\x98Access-Control-Allow-Origin\xe2\x80\x99 missing)\n
Run Code Online (Sandbox Code Playgroud)\n\n

我在 Node js 之上使用了 Reactjs 和 Express。在这里,我尝试从 Agora 服务器播放直播视频,但它没有播放。当我检查控制台时,显示了上述错误。我尝试了一些 Cors 插件到 chrome,它工作得很好。\n我们如何通过直接在express-react环境中添加此标头来解决这个问题?

\n\n

从一些教程中我添加了以下内容来解决它:

\n\n
var config = {\nentry: APP_DIR + \'/index.jsx\',\nheaders: {\n    "Access-Control-Allow-Origin": "http://localhost:3000",\n    "Access-Control-Allow-Credentials": "true",\n    "Access-Control-Allow-Headers": "Content-Type, Authorization, x-id,   \n    Content-Length, X-Requested-With",\n    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"\n},\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的 server.js 文件:

\n\n
    var path = require(\'path\');\n    var webpack = require(\'webpack\');\n    var express = require(\'express\');\n    var config = require(\'./webpack.config\');\n\n     var app = express();\n    var compiler = webpack(config);\n\n    app.use(require(\'webpack-dev-middleware\')(compiler, {\n   publicPath: config.output.publicPath\n   }));\n\n  app.use(function(req, res, next) {\n  res.header("Access-Control-Allow-Origin", "http://localhost:3000");\n  res.header("Access-Control-Allow-Credentials", "true");\n  res.header("Access-Control-Allow-Headers", "Origin,Content-Type,   Authorization, x-id, Content-Length, X-Requested-With");\n  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");\n  next();\n  });\n\n  app.use(require(\'webpack-hot-middleware\')(compiler));\n\n  app.get(\'*\', function(req, res) {\n  res.sendFile(path.join(__dirname, \'index.html\'));\n  });\n\n app.listen(3000, function(err) {\n  if (err) {\n    return console.error(err);\n }\n\n  console.log(\'Listening at http://localhost:3000/\');\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

但它仍然不起作用。

\n\n

您能建议我解决这个问题吗?

\n

Shu*_*tri 5

您需要从服务器发送以下标头NodeJS,而不是在ReactJSwebpack 配置中指定这些标头。

将以下行添加到您的NodeJs服务器代码中

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Headers", "Origin,Content-Type, Authorization, x-id, Content-Length, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    next();
});
Run Code Online (Sandbox Code Playgroud)