python3 tornado api + angular8 + nginx cross-domain issues

Problem :

After deployed on a blog the api, the front began hanging find a cross-domain problems.

Interface address :

http://111.231.201.164/api/houses   used on the server is nginx forwards

Data :

 

 

Distal angular request

this.http.get('http://111.231.201.164/api/houses').subscribe((res: any) => {
      console.log(res);
});

 

Currently testing two of Google and Firefox.

 Google  browser 

Note that happened to my Google browser has been cross-domain configuration, the server code, whether that is a cross-domain Can my browser can access api.

 

 

 At this time, not disposed in the background or cross-domain nginx.

Firefox browser

And as always, Firefox or cross-domain issues

 

 

 

 

 

 Resolution process :

1, I first configuration of the tornado, although no birds use

This is most of the online tutorial are so to say, but it did not work.

class BaseHandler (tornado.web.RequestHandler):
     # blog.csdn.net/moshowgame solve cross-domain problems 
    DEF set_default_headers (Self):
        self.set_header("Access-Control-Allow-Origin", "*") # 这个地方可以写域名
        self.set_header("Access-Control-Allow-Headers", "token")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Allow-Credentials', 'true')

    def write(self, chunk):
        self.set_header('Access-Control-Allow-Origin', '*')
        super(BaseHandler, self).write(chunk)


class MainHandler(BaseHandler):
    @decoratore
    def get(self):
        self.write("Hello, World")
# 访问: http://localhost:8888/story/sishen232

# 显示:U get story id is sishen232

class HouseHandler(BaseHandler):
    '''house class'''

    def __init__(self, application, request):
        '''必填参数'''
        super().__init__(application, request)
        # 预处理
        self.data = ByteData(self.request.arguments)
        self.params = ['title', 'position', 'size', 'address']

    @decoratore
    def post(self):
        '''提交House接口'''
        # # 判断提交参数是否有误
        # if(('title' not in raw_data) or ('position' not in raw_data)):
        #     self.write(json.dumps(
        #         {"false": {"msg": '参数错误'}}, ensure_ascii=False))
        #     return
        code = paramsCheck(self.data,  self.params)
        if code == 1:
            raw_data = self.data
            if('year' not in raw_data):
                raw_data['year'] = ''
            print(raw_data)
            data = self.application.db.execute(
                "insert into house(title, position, size, address, year) values('{}', '{}', {}, '{}', '{}')".format(raw_data['title'], raw_data['position'], float(raw_data['size']), raw_data['address'], raw_data['year']))
            # self.write(json.dumps({"sum": s}))
            self.write(json.dumps(
                {"success": {"msg": '添加成功'}}, ensure_ascii=False))
        else:
            self.write(json.dumps(
                {"false": {"msg": '参数错误'}}, ensure_ascii=False))

    def get(self, House_id=''):
        '''
            # 获取House接口
            # House_id 存在则获取该条数据,不存在获取所有数据
        '''
        sql = 'select * from house' if House_id == '' else 'select * from house where id = {id}'.format(
            id=House_id)
        data = self.application.db.query(sql)
        # self.write(json.dumps({"sum": s}))
        self.write(json.dumps(
            {"success": {"msg": '获取成功', "data": data}}, ensure_ascii=False))

2、nginx配置

方法1没有起作用的话,那多半就是转发出的问题。

location /api/{
        allow 111.231.201.164;
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://127.0.0.1:8888/;
     ## 跨域
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' "GET, POST, PUT, DELETE, PATCH, OPTIONS";
            add_header 'Access-Control-Allow-Headers' "token";
            return 200;
        }
    }

修改之后重启nginx。

Google浏览器

还是一样ok

 

 

 

 Firefox 浏览器

也请求到了

 

 

 

 

到此跨域问题解决。

 

 

class  BaseHandler( tornado.web.RequestHandler ) :
     # blog.csdn.net/m
 
 
 
oshowgame 解决跨域问题
     def  set_default_headers ( self ):
         self.set_header( "Access-Control-Allow-Origin""*"# 这个地方可以写域名
         self.set_header( "Access-Control-Allow-Headers""token")
         self.set_header( 'Access-Control-Allow-Methods''POST, GET, OPTIONS')
         self.set_header( 'Access-Control-Allow-Credentials''true')

     def  write ( self ,  chunk ):
         self.set_header( 'Access-Control-Allow-Origin''*')
         super(BaseHandler,  self).write(chunk)


class  MainHandler( BaseHandler ) :
     @decoratore
     def  get ( self ):
         self.write( "Hello, World")
# 访问: http://localhost:8888/story/sishen232

# 显示:U get story id is sishen232

class  HouseHandler( BaseHandler ) :
     '''house class'''

     def  __init__ ( self ,  application ,  request ):
         '''必填参数'''
         super().__init__(application, request)
         # 预处理
         self.data  = ByteData( self.request.arguments)
         self.params  = [ 'title''position''size''address']

     @decoratore
     def  post ( self ):
         '''提交House接口'''
         # # 判断提交参数是否有误
         # if(('title' not in raw_data) or ('position' not in raw_data)):
         #     self.write(json.dumps(
         #         {"false": {"msg": '参数错误'}}, ensure_ascii=False))
         #     return
        code  = paramsCheck( self.data,   self.params)
         if code  ==  1:
            raw_data  =  self.data
             if( 'year'  not  in raw_data):
                raw_data[ 'year'=  ''
             print(raw_data)
            data  =  self.application.db.execute(
                 "insert into house(title, position, size, address, year) values(' {} ', ' {} ',  {} , ' {} ', ' {} ')".format(raw_data[ 'title'], raw_data[ 'position'],  float(raw_data[ 'size']), raw_data[ 'address'], raw_data[ 'year']))
             # self.write(json.dumps({"sum": s}))
             self.write(json.dumps(
                { "success": { "msg"'添加成功'}},  ensure_ascii = False))
         else:
             self.write(json.dumps(
                { "false": { "msg"'参数错误'}},  ensure_ascii = False))

     def  get ( self ,  House_id = '' ):
         '''
            # 获取House接口
            # House_id 存在则获取该条数据,不存在获取所有数据
        '''
        sql  =  'select * from house'  if House_id  ==  ''  else  'select * from house where id =  {id} '.format(
             id =House_id)
        data  =  self.application.db.query(sql)
         # self.write(json.dumps({"sum": s}))
         self.write(json.dumps(
            { "success": { "msg"'获取成功'"data": data}},  ensure_ascii = False))

Guess you like

Origin www.cnblogs.com/shuangzikun/p/12021788.html