我正在尝试通过socket.io套接字在有角6客户端和龙卷风服务器之间建立通信。我收到了followint错误:
在客户端:
Access to XMLHttpRequest at 'http://127.0.0.1:8888/socket.io/?
EIO=3&transport=polling&t=MSHp-m5' from origin 'http://localhost:4200' has
been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
在服务器端:
WARNING:tornado.access:404 GET /socket.io/?EIO=3&transport=polling&t=MSHp-m5
(127.0.0.1) 1.00ms
我有一个用python 2.7编写的用Tornado编写的服务器,这是代码:
from tornado import websocket, web, ioloop , httpserver
import json
import socketio
from urlparse import urlparse
cl = []
class SocketHandler(websocket.WebSocketHandler):
def check_origin(self, origin):
print "check origin"
return True
def open(self):
if self not in cl:
cl.append(self)
self.write_message("connection opened")
def on_close(self):
if self in cl:
cl.remove(self)
print "connection closed"
def on_message(self, message):
print "Message received: {}".format(message)
self.write_message("message received")
if __name__ == '__main__':
app = web.Application([
(r'/ws', SocketHandler),
# (r'/api', ApiHandler),
(r'/(favicon.ico)', web.StaticFileHandler, {'path': '../'}),
(r'/(rest_api_example.png)', web.StaticFileHandler, {'path': './'}),
], user_settings={"websocket_allow_origin": "*"})
app.listen(8888)
ioloop.IOLoop.instance().start()
我还有一个用Angular 6编写的客户端,该客户端使用socket.io启动与服务器的会话。该客户端目前在localhost:4200上运行,但将来将在与该服务器不同的计算机上运行,并且不会由该服务器呈现,这意味着我不能仅在与该服务器相同的端口上运行该客户端,因为这不符合我的需求。
这是来自的角度服务代码,用于处理与服务器的通信。
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable,BehaviorSubject} from 'rxjs';
import {delay,map,catchError} from 'rxjs/operators';
import * as io from 'socket.io-client';
@Injectable({providedIn: 'root'})
export class PysystemRunnerService {
private PDB_WEB_PORT = "23456";
private editUrl: string = 'http://127.0.0.1:' + this.PDB_WEB_PORT +
'/l1commands/pysystem_runner_edit_list';
private socket;
private socket_port = "8888";
private socketUrl = "ws://127.0.0.1:" + this.socket_port + "/ws"
constructor(private http: HttpClient) {
this.socket = io(this.socketUrl);
}
handleEdit(data) {
var ans = this.http.post(this.editUrl, data).pipe(
delay(100),
map((data: any) => (data.data || data)), //TODO fix data type
catchError(this.handleError)
);
return ans;
}
handleRun(data) {
///////////////socket logic////////////////
////////////////////////////
}
public getMessages = () => {
return Observable.create((observer) => {
this.socket.on('new-message', (message) => {
observer.next(message);
});
});
}
//handle http errors
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
我正在阅读龙卷风文档,它说使check_origin函数返回True应该可以解决CORS问题,但是没有。