How to fix “Access-Control-Allow-Origin” error in a python socket-io server

I'm creating a project that uses Vue.js (as a client) and Python (as a server). Python is used for some calculation and the Vue.js is used for the interface. I'm connecting them using python-socketio (https://python-socketio.readthedocs.io/en/latest/) and Vue-socket.io (https://github.com/MetinSeylan/Vue-Socket.io). Some weeks ago it was working just fine. The connection and communication was happening succefully. But a couple days ago I tried running the same code again and this error appeared:

► Access to XMLHttpRequest at shttp://localhost:2003/socket.io/?EI0.38transport.polling&t=Mom6k2V' from origin 'http://1 :1 ocalhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
► GET http://localhost:2003/socket.io/?EI0=3&transport=polling&t=Mom6k2V net::ERR FAILED vue-socketio.js?5132:8

I tried using old repositories that i knew for sure that were working but I got the same problem.

I tried running the same code in another computer and in a Raspberry Pi and got the same problem.

I tried running chrome with --disable-web-security in order to disable cors but I got the following error:

► WebSocket connection to 'ws://localhost:2003/socket.io/? vue-socketio.js?5132:10 EI0.3&transport=websocket&sid=7111830544fa4dfd98c3424afd25c10e failed: Error during WebSocket handshake: Unexpected response code: 400 


# -*- coding: utf-8 -*-
import eventlet
import socketio
import numpy as np
import json
import serial
import threading
from scipy.integrate import odeint

sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}

def connect(sid, env):
    print('conectado ', sid)

def disconnect(sid):
    print('desconectado ', sid)

# Other functionalities in the code 

if __name__ == '__main__':
    thread = threading.Thread(target=leitura_dados, args=(ser,))
    eventlet.wsgi.server(eventlet.listen(('', 2003)), app)

Connection in the client

Vue.use(new VueSocketIO({
  debug: false,
  connection: 'http://localhost:2003'

I expected it to work as it did before. Without any CORS error or error during handshake. I have no idea why it suddenly stopped working.


Looking a little bit deeper into the docs (https://python-socketio.readthedocs.io/en/latest/api.html?highlight=cors#server-class) I finally found the answer. Instead of:

sio = socketio.Server()


sio = socketio.Server(cors_allowed_origins='*')


sio = socketio.AsyncServer(cors_allowed_origins=['*']) # * is bad

client.js - Extra arg required:

let socket = io("http://localhost:8080",
{transports: ['websocket', 'polling', 'flashsocket']}

copied! https://github.com/socketio/socket.io-client/issues/641#issuecomment-38276289

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

  • How to use backbone.js with websockets/socket-io/nowjs
    I am just getting into backbone.js and am finding progress a little slow. My main problem is working out how to keep my client and server side models in sync using socket-io (technically I am using now.js but the same principal should apply). I think the best way is to override the sync method but some simple advice would be really welcome.
  • 如何解决“缺少跨域资源共享(CORS)响应标题” webfont问题?(How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?)
    问题 由于某些原因,字体已停止在我的网站上呈现。 字体存储在本地,与站点位于同一台服务器上。 我查了一下问题,这似乎是Missing Cross-Origin Resource Sharing (CORS) Response Header但我无法理解解决方案。 据说所有各种站点都使用: Access-Control-Allow-Origin:* 但是由于我主要是前端,所以我不知道该放在哪里。 这是我的房东可以帮助的吗? 我该怎么做才能解决此问题? 编辑: 有问题的网站是:http://cyclistinsuranceaustralia.com.au/ 例如,右上角的电话号码应为Bebas字体,但默认为Impact。 在控制台中,出现错误: 跨域资源共享策略已阻止加载来源“ http://www.cyclistinsuranceaustralia.com.au”中的字体:“ Access-Control-Allow-Origin”标头的值为“ http:// www”。 cyclistinsuranceaustralia.com.au”不等于所提供的来源。 因此,不允许访问来源“ http://cyclistinsuranceaustralia.com.au”。 我联系我的房东,他说: Access-Control-Allow-Origin "http://www
  • Angular 2中的访问控制允许原点问题(Access Control Allow Origin issue in Angular 2)
    问题 我从node.js服务器获取数据时遇到问题。 客户端是: public getTestLines() : Observable<TestLine[]> { let headers = new Headers({ 'Access-Control-Allow-Origin': '*' }); let options = new RequestOptions({ headers: headers }); return this.http.get('http://localhost:3003/get_testlines', options) .map((res:Response) => res.json()) .catch((error:any) => Observable.throw(error.json().error || 'Server error')); } 在服务器端,我还设置了标头: resp.setHeader('Access-Control-Allow-Origin','*') resp.send(JSON.stringify(results)) 但我得到一个错误 “ XMLHttpRequest无法加载http:// localhost:3003 / get_testlines。对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control
  • CORS-使用AJAX在Python(webapp2)网络服务上发布(CORS - Using AJAX to post on a Python (webapp2) web service)
    问题 这会很长: 好的,所以我正在开发一个Google日历小工具,它将请求发送到托管在Google App Engine上的Python webapp2 REST api。 当我尝试发布某些由于CORS不允许我执行的操作时,问题就来了。 在Chrome的DevTools中显示: Method: OPTIONS. Status: (failed) Request header field Content-Type is not allowed by Access-Control-Allow-Headers. Origin https://hq34i4geprnp5vci191ljfuhcoerscl4-a-calendar-opensocial.googleusercontent.com is not allowed by Access-Control-Allow-Origin. 我知道这是因为CORS。 这里: Ajax-'Origin localhost不允许Access-Control-Allow-Origin' 它说我必须添加 Access-Control-Allow-Origin: * 对于标题,但是再说一次,我还是ajax的新手,我想知道它是否是通过这种方式完成的: $.ajax({ type: "POST", url: "https://myapp.appspot
  • Javascript-所请求的资源上没有“ Access-Control-Allow-Origin”标头(Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource)
    问题 我需要通过XmlHttpRequest将数据从JavaScript发送到Python服务器。 因为我使用的是localhost,所以我需要使用CORS。 我正在使用Flask框架及其模块flask_cors 。 作为JavaScript,我有这个: var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST", "http://localhost:5000/signin", true); var params = "email=" + email + "&password=" + password; xmlhttp.onreadystatechange = function() {//Call a function when the state changes. if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { alert(xmlhttp
  • jQuery的CORS错误(CORS error with jquery)
    问题 我目前正在使用cloudapp API进行项目,并且正在使用jquery。 这是我的代码: $.ajax({ headers: { "Accept": "application/json"}, type: 'GET', url: 'http://cl.ly/2wr4', crossDomain: true, success: function(data, textStatus, request){ console.log(data); } }); 当我运行它时,我得到200 OK响应,并且在Firefox中出现此错误: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://cl.ly/2wr4. This can be fixed by moving the resource to the same domain or enabling CORS. 以及Google Chrome浏览器中的此错误: XMLHttpRequest cannot load http://cl.ly/2wr4. No 'Access-Control-Allow-Origin' header is present on the requested
  • 在Golang中启用CORS(Enable CORS in Golang)
    问题 嗨,我正在实现rest api,为此,我想允许跨源请求得到服务。 我目前正在做什么: AWS上的转到服务器代码: func (c *UserController) Login(w http.ResponseWriter, r *http.Request, ctx *rack.Context) { w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") ... ... c.render.Json(w,rsp, http.StatusOK) return } 本地主机上的Ajax代码: <script> $( document ).ready(function() { console.log( "ready!" ); $.ajax({ url: 'http://ip:8080/login', crossDomain: true, //set as a cross domain requests withCredentials:false, type: 'post', success: function (data) { alert(
  • JavaScript-XMLHttpRequest,Access-Control-Allow-Origin错误(JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors)
    问题 我正在尝试将XMLHttpRequest发送到粘贴站点。 我正在发送一个对象,其中包含api所需的所有字段,但我一直遇到此问题。 我已经阅读了这个问题,并认为: httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); 可以修复它,但是没有。 是否有人对此错误和/或如何解决有任何信息? 这是我的代码: (function () { 'use strict'; var httpReq = new XMLHttpRequest(); var url = 'http://paste.ee/api'; var fields = 'key=public&description=test&paste=this is a test paste&format=JSON'; var fields2 = {key: 'public', description: 'test', paste: 'this is a test paste', format: 'JSON'}; httpReq.open('POST', url, true); console.log('good'); httpReq.setRequestHeader('Access-Control-Allow-Headers', '*'); httpReq
  • socket.io-ReferenceError:未定义io(socket.io - ReferenceError: io is not defined)
    问题 我正在为Android 2.3.5(也将与iOS兼容)编写一个应用程序。 我希望将数据从应用程序的HTML / Javascript传输到服务器上的Python程序(该服务器使用Twisted引擎检索数据)。 我尝试了很多事情,并浏览了各种论坛,答案,教程和网页-包括此处的大多数内容-找不到答案。 这是我的index.html文件中包含的相关Javascript: <script src="socket-lib/socket.io.js"></script> <script type="text/javascript" charset="utf-8"> function sendData() { try { var socket = io.connect('http://mywebsite.com:12345'); socket.on('connect', function(data) { socket.send('Hello.'); socket.on('message', function (msg) { socket.send('This is where I send data?'); }); }); } catch(err) { alert('ERROR: socket.io encountered a problem:\n\n' + err); } } //
  • 如何在Flask中设置响应头?(How do I set response headers in Flask?)
    问题 这是我的代码: @app.route('/hello', methods=["POST"]) def hello(): resp = make_response() resp.headers['Access-Control-Allow-Origin'] = '*' return resp 但是,当我从浏览器向服务器发出请求时,出现此错误: XMLHttpRequest cannot load http://localhost:5000/hello. No 'Access-Control-Allow-Origin' header is present on the requested resource. 我也尝试过这种方法,在请求之后设置响应头: @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' return response 没有骰子。 我犯了同样的错误。 有没有一种方法可以只在route函数中设置响应头? 这样的事情将是理想的: @app.route('/hello', methods=["POST"]) def hello(response): # is this a thing?? response.headers[
  • 将jQuery帖子发送到Google API的Access-Control-Allow-Origin错误(Access-Control-Allow-Origin error sending a jQuery Post to Google API's)
    问题 我读了很多有关“ Access-Control-Allow-Origin”错误的信息,但是我不明白我必须解决的问题:( 我正在使用Google Moderator API,但是当我尝试添加新的系列时,收到以下消息: XMLHttpRequest cannot load https://www.googleapis.com/moderator/v1/series?key=[key] &data%5Bdescription%5D=Share+and+rank+tips+for+eating+healthily+on+the+cheaps! &data%5Bname%5D=Eating+Healthy+%26+Cheap &data%5BvideoSubmissionAllowed%5D=false. Origin [my_domain] is not allowed by Access-Control-Allow-Origin. 我尝试使用和不使用回调参数,都尝试在标头中添加“ Access-Control-Allow-Origin *”。 而且我不知道如何在这里使用$ .getJSON(如果适用),因为我必须添加Authorization标头,而且我不知道如何在没有$ .ajax的beforeCall的情况下进行操作:/ 这个黑暗的uu有光吗? 那是代码: <script
  • Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource
    I need to send data through XmlHttpRequest from JavaScript to Python server. Because I'm using localhost, I need to use CORS. I'm using the Flask framework and its module flask_cors. As JavaScript I have this: var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST", "http://localhost:5000/signin", true); var params = "email=" + email + "&password=" + password; xmlhttp.onreadystatechange = function() {//Call a function when the
  • 用Flask解决跨源资源共享(Solve Cross Origin Resource Sharing with Flask)
    问题 对于以下针对Flask ajax发布请求(如何使用烧瓶中从ajax发布的数据?): $.ajax({ url: "", type: "POST", contentType: "application/json", data: JSON.stringify({'inputVar': 1}), success: function( data ) { alert( "success" + data ); } }); 我收到跨源资源共享(CORS)错误: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 500. 我尝试通过以下两种方式解决该问题,但似乎没有任何效果。 使用Flask-CORS 这是用于处理CORS的Flask扩展程序,该扩展程序应使跨域AJAX成为可能。 http://flask-cors.readthedocs.org/en/latest/ 如何在Flask和Heroku中启用CORS 应用jwt auth包装器时,flask-cors包装器不起作用。
  • Mean.io framework with socket.io
    How to use socket.io in Mean.io stack? First of all, Mean.io changes their folder structure very regularly.. So my question is where is the best place to configure socket.io ? or is it better to use express.io ? Second I am still not quite sure where to look for to find code that tells mean.io to listen for port, I have found a port is defined in config folder in all.js file, but real problem is as soon as I define server.listen(port) app doesn't load. and if I don't app loads but socket.io doesn't work. Also I have another question about /socket.io/socket-io.js file? I have copied that in
  • 如何绕过Access-Control-Allow-Origin?(how to bypass Access-Control-Allow-Origin?)
    问题 我正在对其设置的平台上的我自己的服务器进行ajax调用,以防止这些ajax调用(但是我需要它来从服务器中获取数据以显示从服务器数据库中检索到的数据)。 我的ajax脚本正在运行,它可以将数据发送到服务器的php脚本以进行处理。 但是,由于"Access-Control-Allow-Origin"阻止了它,因此无法取回已处理的数据。 我无权访问该平台的源/核心。 因此我无法删除不允许这样做的脚本。 (P / SI使用了Google Chrome浏览器的控制台,并发现了此错误) Ajax代码如下所示: $.ajax({ type: "GET", url: "http://example.com/retrieve.php", data: "id=" + id + "&url=" + url, dataType: 'json', cache: false, success: function(data) { var friend = data[1]; var blog = data[2]; $('#user').html("<b>Friends: </b>"+friend+"<b><br> Blogs: </b>"+blog); } }); 还是上面的ajax脚本具有JSON等效代码? 我认为JSON是允许的。 我希望有人可以帮助我。 回答1 把它放在retrieve.php之上:
  • How do I set response headers in Flask?
    This is my code: @app.route('/hello', methods=["POST"]) def hello(): resp = make_response() resp.headers['Access-Control-Allow-Origin'] = '*' return resp However, when I make a request from the browser to my server I get this error: XMLHttpRequest cannot load http://localhost:5000/hello. No 'Access-Control-Allow-Origin' header is present on the requested resource. I have also tried this approach, setting the response headers "after" the request: @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' return response No dice. I get the same error. Is
  • 未捕获(按承诺)TypeError:无法获取和Cors错误(Uncaught (in promise) TypeError: Failed to fetch and Cors error)
    问题 从数据库取回数据时遇到问题。 我正在尽力解释这个问题。 1.如果在下面的代码中保留“ mode”:“ no-cors”,则可以使用Postman从服务器获取数据,而不能使用自己的服务器获取数据。 认为这一定是我的客户端错误 当我删除“ mode”:“ no-cors”时,我得到2个错误:-Fetch API无法加载http:// localhost:3000 /。 在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段access-control-allow-origin。 -未捕获(承诺)TypeError:无法获取 Quick Browsing建议将“ mode”:“ no-cors”置于其中,以解决此错误,但是这样做并不对劲。 所以我想也许有人对如何解决这个问题提出了建议。 真的希望我已经足够清楚,但是可以肯定的是,我在这里没有给出明确的解释: function send(){ var myVar = {"id" : 1}; console.log("tuleb siia", document.getElementById('saada').value); fetch("http://localhost:3000", { method: "POST", headers: { "Access-Control-Allow-Origin"
  • vue项目连接socket.io跨域及400异常处理
    最近看人家用socket.io聊天,于是自己也想打个服务试试,不试不知道,一试吓一跳,原来这里吗还有这么多坑,下面就是所遇的坑,记录一哈,但愿可以帮助到遇到同样的坑的小伙伴 文章目录 一、服务端配置1、首先创建一个目录2、再创建一个nodejs项目目录3、初始化一个nodejs项目4、安装依赖5、再在目录下新增一个app.js6、运行测试 二、创建一个vue项目1、创建一个vue目录2、安装socket依赖3、修改main.js4、修改HelloWorld.vue5、启动项目 三、项目测试四、使用docker发布服务1、配置Dockerfile2、创建镜像3、创建容器 五、配置nginx代理六、跨域处理七、处理400异常 一、服务端配置 这里我使用nodejs 作为我的后台服务 1、首先创建一个目录 D:\learnVUE>mkdir socketIOTest 2、再创建一个nodejs项目目录 D:\learnVUE>cd socketIOTest D:\learnVUE\socketIOTest>mkdir nodejsProj 3、初始化一个nodejs项目 D:\learnVUE\socketIOTest>cd nodejsProj D:\learnVUE\socketIOTest\nodejsProj>npm init -y 4、安装依赖 D:\learnVUE
  • CORS Access-Control-Allow-Origin despite correct headers
    I am trying to set up simple Cross-Origin Resource Sharing using jQuery (1.7.1) powered ajax on the client and apache served python (django) server. According to all the instructions I have read my headers are set correctly, but I keep getting the following error: XMLHttpRequest cannot load http://myexternaldomain.com/get_data. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. The header being I am trying to (I am not sure it is even getting past the browser) send is: Request URL:http://myexternaldomain.com/get_data Accept:application/json, text/javascript, */*; q=0
  • 隐秘的“脚本错误”。 在Chrome和Firefox中以Javascript报告(Cryptic “Script Error.” reported in Javascript in Chrome and Firefox)
    问题 我有一个脚本,该脚本可以在我的网站上检测Javascript错误并将其发送到我的后端进行报告。 它报告遇到的第一个错误,假定的行号和时间。 编辑以包含doctype: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml"> ... <script type="text/javascript"> //<![CDATA[ // for debugging javascript! (function(window){ window.onerror = function(msg, url, ln) { //transform errors if (typeof(msg) === 'object' && msg.srcElement && msg.target) { if(msg.srcElement == '[object HTMLScriptElement]' && msg