tornado 添加请求头进行允许跨域

什么是跨域?

这个例子是csdn找的, 声明下哈

什么是跨域? 跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。 所谓同源是指,域名,协议,端口均相同,不明白没关系,举个栗子: http:
//www.123.com/index.html 调用 http://www.123.com/server.php (非跨域) http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域) http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域) http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域) http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域) 请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

 

 

 服务端进行跨域需要添加的代码:

class BaseHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        print("setting headers!!!")
        self.set_header("Access-Control-Allow-Origin", "*") # 这个地方可以写域名
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')

    def post(self):
        self.write('some post')

    def get(self):
        self.write('some get')

    def options(self):
        # no body
        self.set_status(204)
        self.finish()

 

 

可以按照前端目录ajax里面代码进行测试

js ---代码未测试

$.ajax({
   url: "http://some_tornado/api",
   type: "POST",
   crossDomain: true,
   data: 'some_data',
   success: function (response) {
     alert(response);
   },
   error: function (xhr, status) {
     alert("error");
   }
 });

 

     

HTTPServerRequest(
    protocol='http', 
    host='127.0.0.1:8000', 
    method='POST', 
    uri='/index', 
    version='HTTP/1.1', 
    remote_ip='127.0.0.1', 
    headers={
                'Host': '127.0.0.1:8000', 
                'X-Requested-With': 'XMLHttpRequest', 
                'Content-Length': '4977', 
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
                'Origin': 'http://127.0.0.1:8000',
                'Referer': 'http://127.0.0.1:8000/index', 
                'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryvxqv8ydaMOJHVHin',
                 'Accept': '*/*', 
                 'Accept-Encoding': 'gzip, deflate, br', 
                 'Connection': 'keep-alive',
                  'Accept-Language': 'zh-CN,zh;q=0.8'}
      )



{'file': [
            {'content_type': 'image/png', 'body': '', 'filename': '2C($GHY%V5J8WXAO2S_M8@4.png'},
             {'content_type': 'image/png', 'body': '', 'filename': '6CLT@ZF9(Y]76$3T(]3U0IY.png'}
         ]
}

 

posted @ 2017-06-06 17:59  我当道士那儿些年  阅读(8578)  评论(1编辑  收藏  举报