Socket.io + Node.js 跨域请求被阻止 [英] Socket.io + Node.js Cross-Origin Request Blocked

查看:61
本文介绍了Socket.io + Node.js 跨域请求被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node 和 socket.io 编写聊天应用程序.它在 Chrome 上运行良好,但 mozilla 给出了启用跨域请求的错误.

I'm using node and socket.io to write a chat application. It works fine on Chrome but mozilla gives an error to enable the Cross-Origin Requests.

跨域请求被阻止:同源策略不允许读取位于 http://waleedahmad.kd.io:3000/socket.io/?EIO=2&transport=polling&t=1401964309281OyDavRDf4WErI-VAAAI.这可以通过将资源移动到同一域或启用 CORS 来解决.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://waleedahmad.kd.io:3000/socket.io/?EIO=2&transport=polling&t=1401964309289-2&sid=1OyDavRDf4WErI-VAAAI. This can be fixed by moving the resource to the same domain or enabling CORS.

这是我启动节点服务器的代码.

Here's my code to start node server.

var express = require('express'),
    app = express(), 
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    path = require('path');
server.listen(3000);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

在客户端.

var socket = io.connect('//waleedahmad.kd.io:3000/');

HTML 页面上的脚本标记.

Script tag on HTML page.

<script type="text/javascript" src="//waleedahmad.kd.io:3000/socket.io/socket.io.js"></script>

我也在应用根目录中使用 .htaccess 文件.(waleedahmad.kd.io/node).

I'm also using .htaccess file in the app root directory. (waleedahmad.kd.io/node).

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

推荐答案

简单的服务器端修复

注意:不要使用socketio"包...使用socket.io";反而.socketio"过时了.一些用户似乎使用了错误的包.

Simple Server-Side Fix

Note: DO NOT USE "socketio" package... use "socket.io" instead. "socketio" is out of date. Some users seem to be using the wrong package.

socket.io v3

文档:https://socket.io/docs/v3/handling-cors/

cors 选项:https://www.npmjs.com/package/cors

const io = require('socket.io')(server, {
  cors: {
    origin: '*',
  }
});

socket.io <v3

const io = require('socket.io')(server, { origins: '*:*'});

io.set('origins', '*:*');

io.origins('*:*') // for latest version

* 单独不起作用,这让我陷入了困境.

* alone doesn't work which took me down rabbit holes.

这篇关于Socket.io + Node.js 跨域请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆