zoukankan      html  css  js  c++  java
  • python3 tornado api + angular8 + nginx 跨域问题

    问题

    上一个博客部署好了api之后,前端开始吊发现了跨域的问题。

    接口地址

    http://111.231.201.164/api/houses  服务器上使用的是nginx转发

    数据

    前端angular请求

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

    目前测试用的Google 和 Firefox两个。

     Google  浏览器

    需要注意的事我的Google浏览器已经配置过跨域,就是说服务器的代码无论可不可以跨域我的浏览器都可以访问api。

     此时还没在后台或者nginx配置跨域。

    Firefox  浏览器

    而Firefox还是一如既往跨域问题

     

     解决过程

    1、我先是配置的tornado,虽然没有鸟用

    这是网上大部分的教程,都是如此说的,但是却没有起作用。

    class BaseHandler(tornado.web.RequestHandler):
        # blog.csdn.net/moshowgame 解决跨域问题
        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 浏览器

    也请求到了

    到此跨域问题解决。

  • 相关阅读:
    Mybatis--->第五节注解完成增删改查
    Mybatis--->新增新功能报错,以前都正常,突然报错
    Mybatis--->limit分页查询
    固定套路--->log4j日志运用-Maven
    Mybatis第三节优化别名--->user
    Mybatis入门第二节--->优化
    Mybatis 报错 java.io.IOException: Could not find resource mybatis-config.xml
    学习Java的第十二天
    学习Java的第十一天
    学习Java的第十天
  • 原文地址:https://www.cnblogs.com/shuangzikun/p/12021788.html
Copyright © 2011-2022 走看看