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'}
         ]
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM