bwangel23
11/4/2016 - 5:08 PM

OpenResty 设置CORS

OpenResty 设置CORS

## 这是放置在conf.d/下的Nginx配置文件
## 这里的 http://localhost:7080 是 Nginx 前端请求的地址

server {                                                                                                                                                              
    listen 80;                                                                                                 
    server_name '172.17.0.2';                                                                                  
                                                                                                               
    location /json {                                                                                           
        if ($request_method = 'OPTIONS') {                                                                     
            more_set_headers 'Access-Control-Allow-Origin: http://localhost:7080';
            more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS';
            #                                                                                                  
            # Tell client that this pre-flight info is valid for 20 days        
            #                                                                                                  
            more_set_headers 'Access-Control-Max-Age: 1728000';                 
            more_set_headers 'Content-Type: text/plain charset=UTF-8';          
            more_set_headers 'Content-Length: 0';                               
            return 204;                                                                                        
        }                                                                                                      
        if ($request_method = 'POST') {                                                                        
            more_set_headers 'Access-Control-Allow-Origin: http://localhost:7080';
            more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS';
        }                                                                                                      
        if ($request_method = 'GET') {                                                                         
            more_set_headers 'Access-Control-Allow-Origin' 'http://localhost:7080';
            more_set_headers 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        }
        rewrite ^/json$ / break;
        proxy_pass http://localhost:8888;                                       
    }                                                                           
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>There is a cors request in this page</title>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
    There is a cors request.

    <p id="result"></p>

    <script>
      $(document).ready(function () {
        $.ajax({
          method: "POST",
          url: "http://172.17.0.2/json",
          data: {
            name: "michael",
            location: "Beijing"
          },
          success: function (data, status, xhr) {
            $("#result").text(data + "  " + status);
            console.log(data, status);
          }
        });
      });
    </script>
</body>
</html>
#!/usr/bin/env python3                                                                                                                                                
                                                                                
                                                                                
import tornado.httpserver                                                       
import tornado.ioloop                                                           
import tornado.options                                                          
import tornado.web                                                              
                                                                                
from tornado.options import define, options                                     
from tornado.escape import json_encode                                          
                                                                                
define("port", default=8888, help="run on the given port", type=int)            
                                                                                
                                                                                   
class MainHandler(tornado.web.RequestHandler):                                     
    def post(self):                                                                
        result = self.request.body_arguments                                       
        for key in result.keys():                                               
            result[key] = [item.decode('utf8') for item in result[key]]         
        result['name'] = "Tornado"                                              
        self.write(json_encode(result))                                         
                                                                                
                                                                                   
def main():                                                                        
    tornado.options.parse_command_line()                                           
    settings = dict(                                                               
            debug=True,                                                            
    )                                                                              
    application = tornado.web.Application([                                        
        (r"/", MainHandler),                                                   
    ], **settings)                                                                 
    http_server = tornado.httpserver.HTTPServer(application)                       
    http_server.listen(options.port)                                               
    tornado.ioloop.IOLoop.current().start()                                        
                                                                                   
                                                                                   
if __name__ == "__main__":                                                         
    main()